randeepsp
randeepsp

Reputation: 3842

simple use of function in shell script

I am trying to use the simple fuinction below. But i get error sayin unary oprator expected and the output is always one. Can any1 help me correct it.

#!/bin/bash
checkit ()
{
if [ $1 = "none" ]
then
     echo "none"
else
     echo "one"
fi
}
checkit

Upvotes: 1

Views: 530

Answers (3)

pavanlimo
pavanlimo

Reputation: 4252

$1 is an argument to the entire script and not to the function checkit(). So send the same argument to the function too.

#!/bin/bash
checkit ()
{
if [ $1 = "none" ]
then
     echo "none"
else
     echo "one"
fi
}

checkit $1

This has to work.

Upvotes: 2

Delan Azabani
Delan Azabani

Reputation: 81384

Surround $1 with quotes like this:

#!/bin/bash
checkit ()
{
if [ "$1" = "none" ]
then
     echo "none"
else
     echo "one"
fi
}
checkit

Upvotes: 0

Philipp
Philipp

Reputation: 49802

Use the [[ keyword instead of the [ builtin:

#!/bin/bash
checkit ()
{
if [[ $1 = none ]]
then
     echo none
else
     echo one
fi
}
checkit

Please read the Bash pitfalls and the Bash FAQ.

Upvotes: 0

Related Questions