我正在尝试在 Linux 中创建一个充当基本计算器的脚本文件。需要传递3个参数或者不传递参数。
如果有3个参数,应该可以这样执行。
./mycalc 1 + 2
the sum of 1 plus 2 equals 3
但如果它没有任何参数,则应显示菜单,询问减法、加法或退出。
这个布局看起来怎么样?我一直在尝试,但每当我运行它时,它都会给我错误,说我需要输入参数,然后在错误之后显示菜单。
op="$2"
if [ $op == "+" ]
then
sum=$(expr $1 + $3)
echo "The sum of $1 plus $3 equals $sum"
elif [ $op == "-" ]
then
diff=$(expr $1 - $3)
echo "The sum of $1 minus $3 equals $diff"
else
while [ $ch != "X" ] || [ $ch != "x" ]
do
read -p "C) Calculation
X) Exit" ch
最佳答案
这是一个“可爱”的答案。稍后我会就您的代码向您提供一些反馈。
#!/bin/bash
case $2 in
+|-) :;;
*) echo "unknown operator: $2"; exit 1;;
esac
declare -A ops=(
["-"]=minus
["+"]=plus
)
printf "%d %s %d equals %d\n" "$1" "${ops["$2"]}" "$3" "$(bc <<< "$*")"
<小时/>
这里是重写,希望展示一些有用的技术和良好实践
#!/bin/bash
user_args () {
case $2 in
+) echo "The sum of $1 plus $3 equals $(( $1 + $3 ))" ;;
-) echo "The sum of $1 minus $3 equals $(( $1 - $3 ))" ;;
*) echo "I don't know what to do with operator '$2'" ;;
esac
}
interactive () {
PS3="Select an operator: "
select choice in plus minus exit; do
case $choice in
plus) operator="+"; break ;;
minus) operator="-"; break ;;
exit) exit;;
esac
done
read -p "First value: " first
read -p "Second value: " second
echo "The sum of $first $choice $second equals $(( $first $operator $second ))"
}
if (( $# == 3 )); then
user_args "$@"
else
interactive
fi
- 使用函数实现模块化
- 用于轻松扩展分支的 case 语句
- select 语句生成菜单并强制输入有效
- bash 的内置算术表达式
- 使用
“$@”传递参数
- 在需要引用的地方引用变量
关于linux - Linux shell 脚本中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29524646/