Zach Kirsch Zach Kirsch - 4 months ago 14
Bash Question

Quoting and Setting $@ to a Variable

I am having trouble resolving how to use double quotes to capture command line arguments in a bash script. I have two files:

hello_world
and
hello world
(notice the space in the second filename).

Of course this works:

#!/usr/bin/env bash
ls "$@"




$ ./quoted_args.sh hello_world "hello world"
hello world hello_world


However, none of the following (very similar) scripts work:

Script A:

#!/usr/bin/env bash
FILES="$@"
ls "$FILES"




$ ./quoted_args.sh hello_world "hello world"
ls: hello_world hello world: No such file or director


Script B:

#!/usr/bin/env bash
FILES=$@
ls "$FILES"




$ ./quoted_args.sh hello_world "hello world"
ls: hello_world hello world: No such file or director


Script C:

#!/usr/bin/env bash
FILES="$@"
ls $FILES




$ ./quoted_args.sh hello_world "hello world"
ls: hello: No such file or directory
ls: world: No such file or directory
hello_world


Script D:

#!/usr/bin/env bash
FILES=$@
ls $FILES




$ ./quoted_args.sh hello_world "hello world"
ls: hello: No such file or directory
ls: world: No such file or directory
hello_world


I feel like I have tried every way of doing this. I would appreciate any help or insight!

Answer

Store $@ into an array to be able to use it safely in other commands:

# populate files array
files=("$@")

# use array
ls "${files[@]}"

# or directly use "$@"
ls "$@"

Also better to avoid using all uppercase variable names in shell scripts.