Skip to main content
Bash ScriptingCentOS

FOR loops in BASH

By April 16, 2013September 12th, 2022No Comments

The last looping structure we look at is the FOR loop. This is often used to enumerate through a list of items such as in the following code:

for U in(bob joe fred)
do
	useradd -m $U
	echo password | passwd --stdin $U
done

For our example script we will creeate list using the output from ls and then print the size and last accessed time of the file. The last accessed time can be gained from the stat command:

#!/bin/bash
#This file was created on 23/02/13
for F in $(ls)
do
 [ ! -f $F ] && continue ##only work with files
 DT=$(stat $F | grep Access | tail -1 | cut -d " " -f2)
 echo "The file $F is $(du -b $F | cut -f1 ) bytes and was last accessed $DT"
done