tags:

views:

43

answers:

3

Hi!

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
A: 

Surround $1 with quotes like this:

#!/bin/bash
checkit ()
{
if [ "$1" = "none" ]
then
     echo "none"
else
     echo "one"
fi
}
checkit
Delan Azabani
ths output is still one. also what is the difference between using = and ==
randeepsp
According to `man [` there is no such thing as using `==` in the expression. `=` compares strings.
Delan Azabani
if i just use the below , it works.if [ "$1" = "none" ] then echo "none" else echo "one" fi
randeepsp
A: 

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.

Philipp
ths output is still one. also what is the difference between using = and ==
randeepsp
if i just use the below it works fine.
randeepsp
Of course the output is `one` because `$1` is empty, not `none`. Please read up some basics about programming in bash.
Philipp
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.
Roman Cheplyaka
The OP started his code with `#!/bin/bash`, not `#!/bin/sh`.
Philipp
+2  A: 

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

pavanlimo
that is the difference between using = and == ?
randeepsp
Always quote your variables: `[ "$1" = "none" ]` ... `checkit "$1"`
glenn jackman
AFAICT there's no difference between "=" and "==" in Bash.
pavanlimo
`[ $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.
pavanlimo
$1 IS the argument to the function checkit (within the body of the function). $1 is the argument to the script OUTSIDE the body of the function - you just happen to be passing the argument to the script as the first parameter to the function
Beano
@randeepsp: answering your question about `=` and `==`: POSIX standard defines only `=` operator (see http://www.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 `==`.
Roman Cheplyaka
@Roman: But the shebang says "bash", not "sh", so it's perfectly fine to use Bash features.
Dennis Williamson
I did not understand the negative vote casted for this answer. `:|`
pavanlimo