好像你想获得X和从第一和第二个参数($1
和$2
)Y和读操作(A,S,d,男)从标准输入。 我修改您的代码一点,以克服原剧本的问题,并根据我的假设提供结果:
#!/bin/bash
# First number.
x=$1
# Second number.
y=$2
# Result of either addition, subtraction, division or multiplication of $x and $y.
result=0
# Reads operation from user.
read -ep "Enter a for add, s for subtract, m for multiply or d for divide: " operation
case $operation in
a) result=$((x + y));;
s) result=$((x - y));;
d) result=$((x/y));;
m) result=$((x * y));;
*) printf '%s: %s\n' "$operation" "Unknown operation" >&2; exit 1;;
esac
printf 'result: %s\n' "$result"
用法示例:(脚本名称为sof.sh)
./sof.sh 5 4
Enter a for add, s for subtract, m for multiply or d for divide: a
result: 9
./sof.sh 5 4
Enter a for add, s for subtract, m for multiply or d for divide: m
result: 20
./sof.sh 5 4
Enter a for add, s for subtract, m for multiply or d for divide: s
result: 1
./sof.sh 5 4
Enter a for add, s for subtract, m for multiply or d for divide: d
result: 1
PS
请注意以下事项:
expr
在古代是shell代码用来做数学的程序。在像bash这样的POSIX shell中,使用$((expression))
。在bash,ksh88 +,mksh/pdksh或zsh中,您还可以使用((expression))
或'let 表达式'。
- 尽管没有在脚本中使用originaly,但在Bash编程时,值得知道的是
[[
是一个类似于(但功能比[
命令更强大)的bash关键字。看到这个Bash FAQ和Test and conditionals。 除非你正在为POSIX sh写作,否则建议使用[[
。 “
”没有机会输入“。不清楚你的意思,你认为你的脚本可以被称为'myscript a 3 4'吗?这是你的输入,否则你必须添加'read x?'在脚本中输入x值“'等等。另外'elif'会更适合你的二次测试。更好的办法是使用'case $ op a)add ... ;;; ....; esac'等。更好地澄清你的Q文本,而不是回应评论。祝你好运。 – shellter
谢谢。我从添加输入的两种方法中改变了一半,并弄糊涂了。 – Bradg89