我正在用Unix编写脚本,但是我需要一种方法来检查在命令行中输入的参数是否是特定的单词。
因此,如果在使用脚本时用户输入:
$ ./script hello
我的脚本可以告诉“hello”作为参数输入并且可以正确显示消息。
如果用户输入“hello”以外的其他内容作为参数,那么我的脚本可以显示另一条消息。
感谢。
答案 0 :(得分:3)
这应该有效:
#!/bin/bash
if [[ $1 == hello ]];then
echo "hello was entered"
else
echo "hello wasn't entered"
fi
答案 1 :(得分:2)
在Bash中,传递给shell脚本的参数存储在名为如下的变量中:
$0 = name of the script.
$1~$n = arguments.
$# = number of arguments.
$* = single string of all arguments: "arg1,arg2,..."
您只需使用if [ $1 == "some string" ]; then ...
答案 2 :(得分:2)
有很多方法可以检查列表中的位置参数。当列表中有多个项目时,您可以使用case
语句而不是if ... elif ... elif ... fi
比较字符串。语法如下:
#!/bin/bash
case "$1" in
"hello" )
printf "you entered hello\n"
;;
"goodbye" )
printf "well goodbye to you too\n"
;;
* )
printf "you entered something I don't understand.\n"
;;
esac
exit 0
<强>输出/用途强>
$ ./caseex.sh hello
you entered hello
$ ./caseex.sh goodbye
well goodbye to you too
$ ./caseex.sh morning
you entered something I don't understand.
答案 3 :(得分:0)
您可以使用$(number)
检索命令行参数例如,第一个参数将以$ 1存在,第二个参数为$ 2等。
您可以在BASH中使用条件(我假设您使用bash)就像任何其他语言一样;但是语法有点不稳定:)。这是给你的链接 http://tldp.org/LDP/Bash-Beginners-Guide/html/chap_07.html
答案 4 :(得分:-1)
如果您确定参数的位置,您可以:
for element in words:
for word in element.split(' '):
print word
如果你不确定:
您可以使用#!/bin/bash
if [[ $1 == SearchWord]];then
echo "SearchWord was entered"
else
echo "SearchWord wasn't entered"
fi
$*