for cycle / loop

For cycle runs once for every argument

Run something.sh script 100 times with parameters from 1 to 100

for i in `seq 100`;do something.sh $i;done

Another way of doing something with found files/directories. Not so effective than using -exec in find command but it will do just fine with small amount of results. Searches for directories which have 750 permissions and makes them group-executable.

for f in `find . -type d -perm 750`;do chmod o+x $f;done

Do something with every entry in file. This example searches for users listed in cron.allow from /etc/shadow. Good way to determine do all these users have password set.

for f in `cat /etc/cron.d/cron.allow`;do grep $f /etc/shadow ;done

Rename files, remove certain string from filename. Current example removes all strings matching “sh?t” like shit, shut, shot etc. from all *.zip files in current directory.  Also generates harmless mv command errors if *.zip filename does not contain any of those strings.

for f in `ls *.zip`;do mv $f `echo $f | sed -e s/sh.t//g`;done

Find users who are removed but homedirs are kept. Also finds all users who have external  authentication provider.

for f in `ls -la /home/ | awk '{print $3;}'`;do if ( ! grep $f /etc/passwd > /dev/null ); then echo $f; fi; done

Find files with acl-s from subdirectories dir1, dir2, dir3

for f in dir1 dir2 dir3 ;do find ./$f -acl ;done

Check open file count for all http processes, if any of them has over 1024 files open, restart httpd service

for f in `ps -ef |grep "/usr/sbin/httpd" |grep -v "grep" |awk '{print $2}'`;do if [ `lsof -p ${f} |wc -l` -gt 1024 ]; then service httpd restart ; break; fi ;done

Unzip all .gz files found from /foo to /bar

for f in `find /foo -name "*.gz"`; do zcat ${f} > /bar/`basename ${f}|sed -e 's/\.gz$//'` ;done

for cycle trough an array

# declare array
declare -A myarray
# add few keys and values into array
myarray["first"]="foo"
myarray["second"]="bar"
myarray[0]=1

for KEY in "${!myarray[@]}"; do
VAL="${myarray[${KEY}]}"
echo "${KEY}:${VAL}"
done

….

Check out also while cycle

If you found this useful, say thanks, click on some banners or donate, I can always use some beer money.