Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - being space-safe when saving $@ in a variable

Tags:

bash

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?

like image 949
Frank Avatar asked May 01 '11 22:05

Frank


2 Answers

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
$
like image 62
Jonathan Leffler Avatar answered Dec 03 '22 04:12

Jonathan Leffler


Why not use the default expansion feature?

for DIR in "${@:-$(pwd)}"; do
    echo $DIR
done
like image 24
Mikel Avatar answered Dec 03 '22 04:12

Mikel