首页 > 解决方案 > My exit commands are not working right

问题描述

I am not exactly sure if i am using the exits correctly. But when i execute the code with something that prints the usage statement it should stop there. It should do one or the other. In my case it is doing both.

cmd="$1" ## the command to find
if [[ $# -ne 1 ]]
        then
                echo "usage: ./findcmd command"
fi
exit=1

path=$(echo $PATH | tr ":" " ")
for dir in $path
        do
                if [[ -x "$dir/$cmd" && -r "$dir/$cmd" ]]
                        then
                                echo "$dir/$cmd"
                                exit 0
                fi
        done
echo "$cmd not on $PATH"
exit=0

OUTPUT:

[112] ./findcmd

usage: ./findcmd command

/usr/local/bin/ **this should not be here

[113] ./findcmd ping

/usr/bin/ping

标签: unix

解决方案


应该是exit [n]

在脚本中,可以使用 exit nnn 命令将 nnn 退出状态传递给 shell(nnn 必须是 0 - 255 范围内的整数)。

它应该在 IF/FOR 块内。

像这样:

cmd="$1" ## the command to find
if [[ $# -ne 1 ]]
    then
        echo "usage: ./findcmd command"
        exit 1
fi

## rest of code to execute if args are correct

推荐阅读