I have a problem when looping over such a variable. I have prepared 2 examples to show the problem.
ex1:
#!/bin/bash
DIRS="$@"
for DIR in $DIRS; do
echo "$DIR"
done
ex2:
#!/bin/bash
for DIR in "$@"; do
echo "$DIR"
done
The second example works as expected (and required). A quick test follows:
$ ex1 "a b" "c"
a
b
c
$ ex2 "a b" "c"
a b
c
The reason, why I want to use the first method is because I want to be able to pass multiple directories to the program or none to use the current dir. Like so:
[ $# -eq 0 ] && DIRS=`pwd` || DIRS="$@"
So, how do I get example 1 to be space-safe?
Use an array instead of a simple variable.
declare -a DIRS
DIRS=("$@")
for d in "${DIRS[@]}"
do echo "$d"
done
This produces the result:
$ bash xx.sh a "b c" "d e f g" h z
a
b c
d e f g
h
z
$
Why not use the default expansion feature?
for DIR in "${@:-$(pwd)}"; do
echo $DIR
done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With