引用并将 $@ 设置为变量
Quoting and Setting $@ to a Variable
我在解决如何使用双引号捕获 bash 脚本中的命令行参数时遇到问题。我有两个文件:hello_world
和 hello world
(注意第二个文件名中的 space)。
当然可以:
#!/usr/bin/env bash
ls "$@"
$ ./quoted_args.sh hello_world "hello world"
hello world hello_world
但是,none 以下(非常相似)脚本有效:
脚本 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
脚本 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
脚本 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
脚本 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
我觉得我已经尝试了所有的方法。我将不胜感激任何帮助或见解!
将 $@
存储到数组中以便能够在其他命令中安全地 使用它:
# populate files array
files=("$@")
# use array
ls "${files[@]}"
# or directly use "$@"
ls "$@"
最好避免在 shell 脚本中使用所有大写变量名。
我在解决如何使用双引号捕获 bash 脚本中的命令行参数时遇到问题。我有两个文件:hello_world
和 hello world
(注意第二个文件名中的 space)。
当然可以:
#!/usr/bin/env bash
ls "$@"
$ ./quoted_args.sh hello_world "hello world"
hello world hello_world
但是,none 以下(非常相似)脚本有效:
脚本 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
脚本 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
脚本 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
脚本 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
我觉得我已经尝试了所有的方法。我将不胜感激任何帮助或见解!
将 $@
存储到数组中以便能够在其他命令中安全地 使用它:
# populate files array
files=("$@")
# use array
ls "${files[@]}"
# or directly use "$@"
ls "$@"
最好避免在 shell 脚本中使用所有大写变量名。