2016-08-01 49 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