Tuesday, February 12, 2013

Useful looping constructs in Bash

Handy "looping" constructs which I frequently use in my Bash scripts & one-liners:

1) loop over files
for FILE in /etc/*; do echo "etc file: $FILE"; done

OR:
for FILE in `find / -type f -name conf`; do 
echo "File with 'conf' in name: $FILE";
done

2) loop over lines in file
cat /etc/hosts | while read LINE; do echo $LINE; done

OR:
while read LINE; do echo $LINE; done < /etc/hosts

3) loop over words in a file
for WORD in `cat /etc/hosts`; do echo $WORD; done

4) loop over elements in array
A=(a b c)
for i in ${A[@]}; do
echo $i
done

Some more advanced (but also useful) constructs:

1) looping over array of functions & executing each function
FUNC_LIST=(func1 func2)

function func1 {
echo 'func1 here'
}

function func2 {
echo 'func2 here'
}

for func in ${FUNC_LIST[@]}; do
eval $func
done

2) passing array to function
ARR=(el1 el2)

function func {
declare -a argArray=("${!1}")
echo "${argArray[@]}"
}

func ARR[@]