0

I just started writing shell scripts in Unix so, I am a total newbie

I want to read the arguments given when the user run the script ex:

sh script -a abc

I want to read for argument -a user gave abc.

My code so far:

if ( $1 = "-a" )
then var=$2
fi
echo $var

I get an error.

3
  • What error are you getting? Commented May 9, 2014 at 11:07
  • script: 1: script: -a: not found Commented May 9, 2014 at 11:09
  • Use square brackets instead of parenthesis: if [ $1 = "-a" ] Commented May 9, 2014 at 11:10

2 Answers 2

3

Bash uses an external program called test to perform boolean tests, but that program is used mostly via its alias [.

if ( $1 = "-a" )

should become

if [ $1 = "-a" ]

if you use [ or

if test $1 = "-a" 
Sign up to request clarification or add additional context in comments.

2 Comments

I had no idea that's what [] was actually doing +1
I think many people don't realize that [ is in fact an executable. Not sure and not able to test it right away, but Bash has an extended/enhanced/improved test, [[ which I think is built-in.
1
#!/bin/sh

if [ $1 = "-a" ]; then
    var=$2
fi
echo $var

You shoud be careful of the space between if and [

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.