我正在尝试创建一条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上找到的大多数内容。