Try the following:
while [ -n "$1" ] do dir="$1" msg="$2" if [ -d "$dir" ]; then echo "$msg dir FOUND" else echo "$msg dir NOT FOUND" fi shift 2 done
Command
shift <n> just shifts the left positional parameters passed to the script from n positions. For example, if you call a script with:
./myscript 1 2 3 4
$1 is "1" and $2 is "2"
but if you shift 2 , then $1 is "3" and $2 is "4".
Thus, the loop consumes 2 parameters per cycle until parameter $1 is empty ( -n "$1" ).
while can be written more elegantly:
while (( $# ))
getting the same result.
You can also check the second parameter ( while [ -n "$2" ] ), but this changes the behavior when the user provides an odd number of parameters:
- in the first case, the last directory will be checked, but you will have a strange message, because
$msg il empty - il in the second case, you will not have strange messages, but the last directory will be quietly checked
The best test parameters at the beginning:
if (( $# % 2 )) then echo "Provide an even number of parameters" exit 1 fi
source share