1

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

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

这是我的代码

for var in "$@"
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 语句

4

2 回答 2

3

If the user enters no arguments, then $@ will be empty -- in other words, your loop runs 0 times. That check needs to happen outside the loop.

Additionally, with your -d and -e checks, you should quote "$file", otherwise if the user entered an empty string as an arg, you will get unexpected behavior (it would be as if no arg had been passed, and in that case -d and -e actually will end up returning true).

于 2013-04-18T04:14:34.287 回答
1

正如FatalError 所暗示for的那样,问题是当没有参数时你永远不会进入循环。

因此,您需要更多类似的东西:

if [ $# -eq 0 ]
then echo "You have not entered a file"
else
    for file in "$@"
    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)。

于 2013-04-18T04:43:39.427 回答