1

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

3 Answers 3

2

$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.

Sign up to request clarification or add additional context in comments.

8 Comments

that is the difference between using = and == ?
Always quote your variables: [ "$1" = "none" ] ... checkit "$1"
AFAICT there's no difference between "=" and "==" in Bash.
[ $var == "" ] ... if the variable $var is empty the test becomes, [ == "" ] and ends up throwing an error. It's always better to quote your variables as @glenn said.
@randeepsp: answering your question about = and ==: POSIX standard defines only = operator (see opengroup.org/onlinepubs/009695399/utilities/test.html), == is an extension supported by some shells and some implementations of test. You should always try to make your scripts portable and hence avoid ==.
|
0

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.

3 Comments

ths output is still one. also what is the difference between using = and ==
Of course the output is one because $1 is empty, not none. Please read up some basics about programming in bash.
Actually I would argue to use [ instead of [[ because [[ is non-standard and is not supported by some shells. Just remember to quote your variables properly.
0

Surround $1 with quotes like this:

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

3 Comments

ths output is still one. also what is the difference between using = and ==
According to man [ there is no such thing as using == in the expression. = compares strings.
if i just use the below , it works. if [ "$1" = "none" ] then echo "none" else echo "one" fi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.