2016-12-02 79 views
1

所以下面是我在我的bash脚本中的代码。我收到一个错误,说二元运算符预期当我给命令2个参数(不给错误,当我给1个参数)。它会改变文件权限,当我给出2个参数,因为我可以看到它时,我做ls -l但它仍然给我这个错误。我如何解决它?Unix bash错误 - 二元运算符预计

for file in [email protected] 
do 
    chmod 755 $file 
done 

if [ -z [email protected] ] 
then 
     echo "Error. No argument." 
     exit $ERROR_CODE_1 
fi 

我已经加入此现在

if [ ! -f "$*" ] 
then 
     echo "Error. File does not exist" 
     exit $ERROR_NO_FILE 
fi 

但现在当我输入超过1种说法只是做一切if语句(即打印error.file不存在),即使文件确实存在。

+0

不要更改您的问题。如果你有一个*新的问题,你应该把它作为一个新的,而不是改变你现有的*问题。 – andlrc

回答

3

这样一种说法:只是问多少参数进行传递:

... 
if [ $# -eq 0 ] 
... 

你得到的错误在你的代码,因为$ @变量扩展到多个字,这让该test命令看起来像这样:

[-z PARM1 parm2 parm3 ...]

+0

你是男人兄弟。非常感谢。 – pogba123

+0

引用'$ @'仍然可以给'-z'多个参数;这些参数中的空白仅保留。 – chepner

+0

,它会教我不经测试就回答!谢谢,@chepner! –

0

裹在双引号中的参数,以避免字splitti Ng和路径扩展:

for file in "[email protected]" 
do 
    chmod 755 "$file" 
done 

if [ -z "$*" ] # Use $* instead of [email protected] as "[email protected]" expands to multiply words. 
then 
     echo "Error. No argument." 
     exit "$ERROR_CODE_1" 
fi 

但是,您可以更改代码一点:

for file # No need for in "[email protected]" as it's the default 
do 
    chmod 755 "$file" 
done 

if [ "$#" -eq 0 ] # $# Contains numbers of arguments passed 
then 
    >&2 printf 'Error. No argument.\n' 
    exit "$ERROR_CODE_1" # What is this? 
fi 
+0

非常感谢兄弟 – pogba123

+0

我已经在问题框中更新了我的代码,并且得到了一个不同的错误,请你能帮助我。我是一名初学者,需要帮助。 – pogba123

2

[email protected]是扩展到所有的参数,它们之间的空间,所以它看起来像:

if [ -z file1 file2 file3 ] 

-z只期望一个单词。您需要使用$*和引用它,所以它扩展成一个字:

if [ -z "$*" ] 

这将扩展到:

if [ -z "file1 file2 file3" ] 

或者只是检查参数的个数:

if [ $# -eq 0 ] 

您还应该在for循环之前进行此检查。并且您应该引用for循环中的参数,因此您不会遇到有空格的文件名问题:

for file in "[email protected]" 
+0

感谢人感激。 – pogba123

+0

我已经在问题框中更新了我的代码,并且正在获取不同的错误,请帮助我。我是一名初学者,需要帮助。 – pogba123

+0

'-f'后面只有一个文件名,但是你将所有的文件名参数合并到一个测试中。 – Barmar