Unix 如何检查是否输入了特定单词作为参数

Unix How to check if a specific word is entered in as an argument

我正在 Unix 中编写脚本,但我需要一种方法来检查在命令行中输入的参数是否为特定单词。

因此,如果在使用脚本时用户键入:

$ ./script hello 

我的脚本可以判断 "hello" 是作为参数输入的,并且可以适当地显示一条消息。

如果用户键入 "hello" 以外的内容作为参数,那么我的脚本会显示另一条消息。

谢谢。

这应该有效:

#!/bin/bash
if [[  == hello ]];then
echo "hello was entered"
else
echo "hello wasn't entered"
fi

您可以使用 $(number)

检索命令行参数

例如,第一个参数将存在于 $1,第二个参数将存在于 $2,依此类推。

您可以在 BASH 中使用条件句(我假设您使用的是 bash),就像任何其他语言一样;但是语法有点靠不住 :)。这是给你的 link http://tldp.org/LDP/Bash-Beginners-Guide/html/chap_07.html

在 Bash 中传递给 shell 脚本的参数存储在如下命名的变量中:

[=10=] = name of the script.
~$n = arguments.
$# = number of arguments.
$* = single string of all arguments: "arg1,arg2,..."

你可以简单地使用 if [ == "some string" ]; then ...

有多种方法可以根据列表检查位置参数。当列表中有多个项目时,您可以使用 case 语句而不是一串 if ... elif ... elif ... fi 比较。语法如下:

#!/bin/bash

case "" 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

Output/Use

$ ./caseex.sh hello
you entered hello

$ ./caseex.sh goodbye
well goodbye to you too

$ ./caseex.sh morning
you entered something I don't understand.

如果您确定参数的位置,您可以:

#!/bin/bash if [[ == SearchWord]];then echo "SearchWord was entered" else echo "SearchWord wasn't entered" fi

万一你不确定:

您可以使用 $*

[ `echo $* | grep $SearchWord| wc -l` -eq 1 ] && echo "Present"|| echo "Not present"