Some exercises in handling parameters in a script:
Using BASH_ARGV to loop through all arguments
#!/bin/bash
#debugging output
[ -f /tmp/debug ] && set -x
#Loop Though the arguments provided
#BASH places arguments in reverse order in BASH_ARGV array
#Start at end of array (ARGC – 1)
for (( i=$(( $BASH_ARGC – 1 )); i>=0; i– )); do
item=”${BASH_ARGV[$i]}”
echo “\$$(( $BASH_ARGC – $i )): $item”
done
Loop through all arguments with special handling of first and last only
#!/bin/bash
[ -f /tmp/debug ] && set -x
##loop through parameters, start with end of BASH_ARGV
for (( loopNumber=1, i=$(( $BASH_ARGC - 1 )); i>=0; i--, loopNumber++ )); do
#do something special for first and last
if [ $i -eq $(( $BASH_ARGC - 1 )) ]; then
conditionalString="(I am the first one!)"
elif [ $i -eq 0 ]; then
conditionalString="(I am the last one!)"
else
unset conditionalString
fi
echo Arg $loopNumber: ${BASH_ARGV[$i]} $conditionalString
done
Loop through all arguments with special handling of first and everything else
#!/bin/bash
[ -f /tmp/debug ] && set -x
##loop through parameters, start with end of BASH_ARGV
for (( loopNumber=1, i=$(( $BASH_ARGC – 1 )); i>=0; i–, loopNumber++ )); do
#if not the last don’t restart dock
if [ $i -eq $(( $BASH_ARGC – 1 )) ]; then
unset conditionalString
conditionalString=”(I am the first)”
else
conditionalString=”(I am not the first)”
fi
echo Arg $loopNumber: ${BASH_ARGV[$i]} $conditionalString
done
Loop through all arguments with special handling of the last and everything else
#!/bin/bash
[ -f /tmp/debug ] && set -x
##loop through parameters, start with end of BASH_ARGV
for (( loopNumber=1, i=$(( $BASH_ARGC – 1 )); i>=0; i–, loopNumber++ )); do
#if not the last don’t restart dock
if [ ! $i -eq 0 ]; then
conditionalString=”(I am not the last)”
else
unset conditionalString
#conditionalString=”(I am the last)”
fi
echo Arg $loopNumber: ${BASH_ARGV[$i]} $conditionalString
done
(WordPress is bugging the heck out of me with the code tags breaking when their are line breaks… sorry, that’s an exercise for the Googler)