0

I want DIR to loop through all the arguments (with space and ""). But this code do not recognize, "cd ef" as one. Dividing them into two. How can I do that?

#test.sh
echo Number of arguments: $#

if [ $# -eq 0 ]
then
  echo "No arguments"
  DIR=.
else 
  DIR="$*"
fi

echo DIR =$DIR
for arg in $DIR;
do 
  echo $arg;
done

Command

#bash test.sh ab "cd ef" 

Output, Number of arguments: 2

But, enumerating 3 elements in the loop as ab, cd, and ef.

I know, I can do,

for arg in "$*";

But that not the solution in this case. Can I use DIR for this purpose? The platform is OSX Mavericks shell.

3
  • 2
    $* is almost never appropriate for use -- it concatenates arguments with the first character of IFS, meaning that if any argument happens to contain the first character of IFS, it's impossible to distinguish between the characters delimiting the arguments and the characters within the arguments. Commented Sep 3, 2014 at 15:08
  • Also, non-exported, non-builtin variables should have at least one lower-case variable to avoid potential namespace conflicts with environment variables and builtins. Commented Sep 3, 2014 at 15:09
  • 1
    BashFAQ #50, mywiki.wooledge.org/BashFAQ/050 is (tangentially) relevant, inasmuch as it addresses many of the same misunderstandings that result in using scalar variables where they aren't appropriate. Commented Sep 3, 2014 at 15:11

2 Answers 2

4

You need to use an array, not a regular scalar variable, for this purpose -- and "$@", not $*:

if (( $# )); then
  dirs=( "$@" )
else
  dirs=( . )
fi

for dir in "${dirs[@]}"; do
  ...
done

See also BashFAQ #5.

Sign up to request clarification or add additional context in comments.

Comments

1

If you don't actually need a variable DIR, you can use a form of parameter expansion:

echo "DIR=${@:-.}"
for dir in "${@:-.}"; do
   ...
done

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.