Reputation: 289
I'm writing a script in Unix but I need a way to check an argument that is entered in the command line is a specific word.
So if when using the script the user types:
$ ./script hello
my script can tell that "hello" was entered as an argument and can display a message appropriately.
And if the user types something other than "hello" as an argument then my script can display another message.
Thanks.
Upvotes: 0
Views: 2484
Reputation: 480
In Bash arguments passed to shell scripts are stored in variables named as follows:
$0 = name of the script.
$1~$n = arguments.
$# = number of arguments.
$* = single string of all arguments: "arg1,arg2,..."
you can simply use if [ $1 == "some string" ]; then ...
Upvotes: 2
Reputation: 281
If you are sure about the position of the argument you can :
#!/bin/bash
if [[ $1 == SearchWord]];then
echo "SearchWord was entered"
else
echo "SearchWord wasn't entered"
fi
Incase you are not sure:
You can use $*
[ `echo $* | grep $SearchWord| wc -l` -eq 1 ] && echo "Present"|| echo "Not present"
Upvotes: 0
Reputation: 84561
There are a number of ways to check positional arguments against a list. When there are a number of items in the list, you can use a case
statement instead of a string of if ... elif ... elif ... fi
comparisons. The syntax is as follows:
#!/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
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.
Upvotes: 3
Reputation: 850
You can retrieve the command line arguments with $(number)
for example the first argument would exist at $1 the second at $2 etc.
You can use conditionals in BASH (I assume you are using bash) just like any other language; however the syntax is a bit wonky :). here is a link for you http://tldp.org/LDP/Bash-Beginners-Guide/html/chap_07.html
Upvotes: 0
Reputation: 22428
This should work:
#!/bin/bash
if [[ $1 == hello ]];then
echo "hello was entered"
else
echo "hello wasn't entered"
fi
Upvotes: 3