2013-04-18 50 views
1

问题是我想回显一个字符串“你没有输入文件”。回声“你还没有输入文件”

简而言之,如果用户在调用Unix脚本后没有任何字面输入,他们将收到该错误消息。

这里是我的代码

for var in "[email protected]" 
do 

file=$var 

if [ $# -eq 0 ] 
then 
    echo "You have not entered a file" 
elif [ -d $file ] 
then 
    echo "Your file is a directory" 
elif [ -e $file ] 
then 
    sendToBin 
else 
    echo "Your file $file does not exist" 
fi 
done 

我无法弄清楚究竟是错的,我相信这件事情在我的第一个if语句

回答

3

如果用户输入任何参数,然后[email protected]将是空的 - 换句话说,你的循环运行0次。该检查需要在循环之外进行。

另外,与你的-d-e检查,你应该引用"$file",否则,如果用户输入一个空字符串作为阿根廷,你会得到意想不到的行为(这将是如同没有ARG已经过去了,在这案件-d-e实际上最终将返回true)。

1

As FatalErrorsuggests,问题在于,如果没有参数,则永远不会输入for循环。

你因此需要更多的东西,如:

if [ $# -eq 0 ] 
then echo "You have not entered a file" 
else 
    for file in "[email protected]" 
    do 
     if [ -d "$file" ] 
     then echo "$file is a directory" 
     elif [ -e "$file" ] 
     then sendToBin # Does this need $file as an argument? Why not? 
     else echo "File $file does not exist" 
     fi 
    done 
fi 

您可以决定是否错误消息应该为脚本的名称作为前缀($(basename $0 .sh)就是我通常使用),以及他们是否应该被发送到标准错误( >&2)。