Bash 脚本说明两个命令在';我已经报名了
作为作业的第一部分,我正在编写bash脚本。如果参数个数为2,则应返回总和;如果不是两个,则应该返回错误消息并退出脚本 但即使我输入两个命令,它仍然会给我错误消息。为什么呢?我在一秒钟前写了一些非常类似的东西——减去数字,效果很好Bash 脚本说明两个命令在';我已经报名了,bash,command-line,terminal,command-line-interface,Bash,Command Line,Terminal,Command Line Interface,作为作业的第一部分,我正在编写bash脚本。如果参数个数为2,则应返回总和;如果不是两个,则应该返回错误消息并退出脚本 但即使我输入两个命令,它仍然会给我错误消息。为什么呢?我在一秒钟前写了一些非常类似的东西——减去数字,效果很好 #!/bin/bash # This script reads two integers a, b and # calculates the sum of them # script name: add.sh read -p "Enter two value
#!/bin/bash
# This script reads two integers a, b and
# calculates the sum of them
# script name: add.sh
read -p "Enter two values:" a b
if [ $# -ne 2 ]; then
echo "Pass me two arguments!"
else
echo "$a+$b=$(($a+$b))"
fi
read
读取标准输入,而您正在使用其计数进行检查的参数($1
,$2
,…)是命令行参数,可以在调用程序时传递给程序。
read -p "Enter two values: " a b additional_garbage
if [[ -z $b ]]; then # only have to test $b to ensure we have 2 values
“额外的_垃圾”是为了防止有趣的用户输入超过2个值,然后$b类似于“2 3 4”,您的算法被破坏
为了防止无效的八进制数字(例如,如果用户输入08
和09
),请强制使用base-10
echo "$a+$b=$(( 10#$a + 10#$b ))"
您需要区分脚本的
两个参数
和从标准输入读取两个值
。。。