我只是想知道如何读取一个字符串,然后比较它。如果是“加”,然后再进行如何比较BASH脚本中的字符串?
#!/bin/bash
echo -n Enter the First Number:
read num
echo -n Please type plus:
read opr
if [ $num -eq 4 && "$opr"= plus ]; then
echo this is the right
fi
我只是想知道如何读取一个字符串,然后比较它。如果是“加”,然后再进行如何比较BASH脚本中的字符串?
#!/bin/bash
echo -n Enter the First Number:
read num
echo -n Please type plus:
read opr
if [ $num -eq 4 && "$opr"= plus ]; then
echo this is the right
fi
#!/bin/bash
echo -n Enter the First Number:
read num
echo -n Please type plus:
read opr
if [[ $num -eq 4 -a "$opr" == "plus" ]]; then
# ^ ^^
# Implies logical AND Use quotes for string
echo this is the right
fi
#!/bin/bash
read -p 'Enter the First Number: ' num
read -p 'Please type plus: ' opr
if [[ $num -eq 4 && $opr == 'plus' ]]; then
echo 'this is the right'
fi
如果你使用bash的话,我强烈建议使用双括号。它们比单个括号好很多;例如,他们可以更加理智地处理未加引号的变量,并且您可以在括号内使用&&
。
如果您使用单支架,那么你应该这样写:
if [ "$num" -eq 4 ] && [ "$opr" = 'plus' ]; then
echo 'this is the right'
fi
我认为OP希望OPR要对字符串“加”不操作“+”相比;) – Tuxdude 2013-03-06 20:01:43
感谢,这是真正的帮助 – 2013-03-06 20:07:04
这是'=',而不是'==',并且不需要额外的引号 – Idelic 2013-03-06 20:38:18
是的,我想用POSIX风格即' =='带'[[...]]'。在''[']'中,我同意推荐'='。使用引号可以避免混淆,特别是当你有一些特殊字符时,这是一种很好的做法。对于像加号这样的字符串是可选的。 – Tuxdude 2013-03-06 20:51:08
在'[]'内需要'=',而不仅仅是推荐。我同意引用是一种很好的做法,但您的评论给人的印象是多余的引号可以解决OP的问题。总的来说,我认为最好在答案中添加一些解释,而不是仅仅倾销代码。 – Idelic 2013-03-06 21:53:38