2016-08-01 52 views
1

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

当然这个工程:

#!/usr/bin/env bash 
ls "[email protected]" 
$ ./quoted_args.sh hello_world "hello world" 
hello world hello_world 

然而,没有下面的(非常相似)脚本的工作:

脚本A:

#!/usr/bin/env bash 
FILES="[email protected]" 
ls "$FILES" 
$ ./quoted_args.sh hello_world "hello world" 
ls: hello_world hello world: No such file or director 

脚本B:

#!/usr/bin/env bash 
[email protected] 
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="[email protected]" 
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 
[email protected] 
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 

我觉得我已经尝试过这样做的各种方式。我将不胜感激任何帮助或见解!

回答

2

商店[email protected]到一个数组,以便能够使用它安全在其他命令:

# populate files array 
files=("[email protected]") 

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

# or directly use "[email protected]" 
ls "[email protected]" 

而且最好避免使用shell脚本全部大写的变量名。

+0

谢谢!所有大写变量会出现什么问题? –

+2

@ZachKirsch没什么。它们通常由shell和应用程序使用,但您可能会重写其他内容。 – 123

+2

Unix shell使用所有的大写环境变量,例如'PATH,LINES,LANG'等等,你可以在使用全部大写变量时重写其中的一个。 – anubhava