如何检查在基于busybox的Unix系统中是否没有传递任何命令行参数?

我正在尝试创建一条if else语句,其中if检查是否存在命令行参数,而else用于何时没有命令行参数。我已经尝试过if if和两个ifs。每当我不带任何参数运行时,都会出现错误:

sh:0:未知操作数

如果我使用命令行参数运行,它将正常工作。 如果我使用if $1运行脚本,则会收到错误消息:

sh:缺少]

这是我最近尝试过的两种情况,

if [ $1 -gt 0 ];
then
    ch=$1
    stri=$2
    thefunction $ch $stri
fi

# User input not working

if [ -z "$1" ];
then
    stat="Y"
    while [ $stat == "[Yy]" ];
    do
        printf "\nPlease enter a choice. Enter 1 for manual.\n"
        read ch
        flag=1
        if [ $ch -eq 3];
        then
            printf "\nPlease enter string to be searched.\n"
            read stri
        fi
        thefunction $ch $stri $flag
        printf "Do you wanna continue? \n Press 'Y' to continue..."
        read stat
    done
fi

if [ $1 -gt 0 ];
then
    ch=$1
    stri=$2
    thefunction $ch $stri
else
    stat="Y"
    while [ $stat == "[Yy]" ];
    do
        printf "\nPlease enter a choice. Enter 1 for manual.\n"
        read ch
        flag=1
        if [ $ch -eq 3];
        then
            printf "\nPlease enter string to be searched.\n"
            read stri
        fi
        thefunction $ch $stri $flag
        printf "Do you wanna continue? \n Press 'Y' to continue..."
        read stat
    done
fi

我还尝试使用多个[[]]代替而不是单个[],if ! $1,以及我可以在Google上找到的大多数内容。

liudongmei2006407114 回答:如何检查在基于busybox的Unix系统中是否没有传递任何命令行参数?

  

如何检查在基于busybox的Unix系统中是否没有传递任何命令行参数?

您检查参数数量是否等于零。

if [ $# -eq 0 ]; then
   echo "No arguments passed"
fi

不带参数的$1扩展为空:

if [ $1 -gt 0 ];

扩展到:

if [ -gt 0 ];

由于-gt 0 ][的无效参数,因此该工具会抱怨。

请注意,bash可以识别空间,3];可能就是3 ];

[ $stat == "[Yy]" ]检查stat是否等于字符串"[Yy]"==[命令的扩展,请改用=。要检查$stat是否等于Yy,请使用[ "$stat" = "y" -o "$stat" = "Y" ]case构造。

本文链接:https://www.f2er.com/3053575.html

大家都在问