【问题标题】:Quoting and Setting $@ to a Variable引用 $@ 并将其设置为变量
【发布时间】:2016-08-01 15:18:08
【问题描述】:

我无法解决如何使用双引号来捕获 bash 脚本中的命令行参数。我有两个文件:hello_worldhello world(注意第二个文件名中的空格)。

当然可以:

#!/usr/bin/env bash
ls "$@"
$ ./quoted_args.sh hello_world "hello world"
hello world hello_world

但是,以下(非常相似的)脚本都不起作用:

脚本 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

我觉得我已经尝试了各种方法。我将不胜感激任何帮助或见解!

【问题讨论】:

    标签: bash command-line-arguments quotes


    【解决方案1】:

    $@ 存储到一个数组中以便能够在其他命令中安全地使用它

    # populate files array
    files=("$@")
    
    # use array
    ls "${files[@]}"
    
    # or directly use "$@"
    ls "$@"
    

    最好避免在 shell 脚本中使用所有大写的变量名。

    【讨论】:

    • @ZachKirsch 没什么。它们通常由 shell 和应用程序使用,因此您可以覆盖其他内容。
    • Unix shell 使用所有大写环境变量,例如PATH, LINES, LANG 等,您可以在使用所有大写变量时覆盖其中一个。
    猜你喜欢
    • 1970-01-01
    • 2014-11-19
    • 1970-01-01
    • 2022-10-12
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 2010-10-13
    • 1970-01-01
    相关资源
    最近更新 更多