gpt4 book ai didi

linux - Bash:否则在 case 语句中的 if/else 语句中不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 12:34:43 25 4
gpt4 key购买 nike

我正在尝试检查用户是否使用 case 和 if/else 语句在命令行中键入多个参数。错误的是我一直在获取默认情况而不是相同的命令,但还有 2 个参数。例如,我的条件之一是:

del)
if [ -z "$2" ] || [ -z "$3" ]
then
echo "Usage: removes a file"
else
echo "using Bash command: rm $2 $3"
rm $2 $3
echo done
fi

打印第一个条件,但是如果我输入,比方说,del aaa bbb,我会得到默认情况,即:

echo "ERROR: Unrecognized command"

如果有帮助的话,我还使用它来读取用户的输入。

read -p "wcl> " -r wcl $2 $3

我真的不知道是否有更好的方法来解决这个问题,而不用废弃我的所有代码并从头开始。这是完整的代码:

#!/bin/bash
#use read command

echo Welcome to the Windows Command Line simulator!
echo Enter your commands below
while true
do
read -p "wcl> " -r wcl $2 $3
case $wcl in
dir)
echo "using Bash command: ls $2 $3"
ls
continue
;;
copy)
FILE="$2"
if [ "$#" -ne 3 ]
then
echo "Usage: copy sourcefile destinationfile"
else
echo "using Bash command: cp $2 $3"
if [ -f "$FILE" ]
then
cp $2 $3
else
echo "cannot stat $FILE: No such file or directory">&2
fi
echo done
fi
continue
;;
del)
if [ -z "$2" ] || [ -z "$3" ]
then
echo "Usage: removes a file"
else
echo "using Bash command: rm $2 $3"
rm $2 $3
echo done
fi
continue
;;
move)
if [ -z "$2" ] || [ -z "$3" ]
then
echo "Usage: moves a file to another file name and location"
else
echo "using Bash command: mv $2 $3"
mv $2 $3
echo done
fi
continue
;;
rename)
if [ -z "$2" ] || [ -z "$3" ]
then
echo "Usage: renames a file"
else
echo "using Bash command: mv $2 $3"
mv $2 $3
echo done
fi
continue
;;
ipconfig)
ifconfig eth0 | grep "inet addr" | cut -d ':' -f 2 | cut -d ' ' -f 1
continue
;;
exit)
echo "Goodbye"
exit 1
;;
^c)
echo "Goodbye"
exit 1
;;
*)
echo "ERROR: Unrecognized command"
continue
esac
done

最佳答案

您不能使用read 来设置位置参数,尽管不清楚为什么您需要在这里。只需使用常规参数即可。

while true
do
read -p "wcl> " -r wcl arg1 arg2
case $wcl in
dir)
echo "using Bash command: ls $arg1 $arg2"
ls "$arg1" "$arg2"
continue
;;

# ...
esac
done

read -r wcl $2 $3 的执行方式是 $2$3 首先展开,给出 read 的名称 将用于设置变量。如果未设置这些,则命令将减少为 read -r wcl,因此您的整个命令行都分配给变量 wcl,而不仅仅是命令。

但是,如果您的目标是编写自己的 shell,则 read 本身不会执行与 shell 已经执行的相同的解析。

关于linux - Bash:否则在 case 语句中的 if/else 语句中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42279337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com