Linux shell脚本,检查来自用户的输入
问题描述:
因此,我正在制作一个简单的bash shell脚本计算器,并遇到了一个障碍。Linux shell脚本,检查来自用户的输入
我似乎无法找出看到,如果用户已经输入+或 - 或/或*
我不知道我应该尝试写。我知道
echo "Enter + or - "
read input2
if [ $input2 = "+" ] then
echo "You entered $input2"
不起作用。那么我应该为基本操作员阅读哪些内容?
编辑:击壳正在使用
答
在bash,分号或then
之前需要换行符。
双引号变量,以防止膨胀可能导致语法错误:
if [ "$input" = '+' ] ; then
您还可以切换到[[ ... ]]
条件语句不需要的参数报价:
if [[ $input = + ]] ; then
echo You entered +
fi
你有在右边引用*
,否则它被解释为通配符模式,意思是“任何事物”。
答
尝试if语句,如:
if [ $input = "+" ]
答
你有一些严重的语法问题。这里有一个精致的一个:
#!/bin/bash
echo "Enter + or - "
read input2
if [ "$input2" = "+" ]; then
echo "You entered $input2"
fi
输出:
Enter + or -
+
You entered +
您可以打印一些与输入时读得。
read -p "Enter + or - " input2
答
一个简单的方法是使用bash case语句,而不是如果这个计算器脚本的条件。
#!/bin/bash
echo "Enter + or - or * or /"
read input2
case $input2 in
'+')
echo "You entered $input2" ;;
'-')
echo "You entered $input2" ;;
'*')
echo "You entered $input2" ;;
'/')
echo "You entered $input2" ;;
*)
echo "Invalid input"
;;
esac
请注意案例'*'和最后一种情况*(不带单引号)之间的区别。第一个将直接匹配'*'符号,但最后一个(没有单引号)表示通配符。最后一个选项是用来捕获所有无效输入的通配符,这些输入与我们正在寻找的任何情况都不匹配。
上面的脚本也可以修改得更短。
echo "Enter + or - or * or /"
read input2
case $input2 in
'+'|'-' |'*' |'/')
echo "You entered $input2" ;;
*)
echo "Invalid input"
;;
esac
这会寻找“+”或“ - ”或“*”或“/”在一个单一的情况下,并打印$输入2否则将默认打印“无效输入”。
您可以在此处详细了解http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_03.html
case语句请务必注明您的变量。否则,'*'将被扩展为文件名通配符。 – Barmar 2015-04-01 15:55:55
你用什么外壳? – choroba 2015-04-01 15:56:36
请发布实际脚本示例。很难说出你做错了什么。我甚至不确定你是否在你的问题中使用反引号作为SO标记,或者因为这是你在脚本中的实际情况。 – Barmar 2015-04-01 15:57:26