I am trying to pass arguments to a function within an if
statement and then evaluating what the function returns (in bash). The result I am getting is incorrect. How do you properly do this?
#!/bin/bash
foo() {
if [ $1 = "zero" ]; then
echo "0"
else
echo "1"
fi
}
arg="zero"
if foo $arg -eq 0 ; then
echo "entered 0"
else
echo "entered something else"
fi
arg="blah"
if foo $arg -eq 0 ; then
echo "entered 0"
else
echo "entered something else"
fi
Not the desired results:
cknight@macbook:~/work$ ./test.sh
0
entered 0
1
entered 0
To pass any number of arguments to the bash function simply put them right after the function's name, separated by a space. It is a good practice to double-quote the arguments to avoid the misparsing of an argument with spaces in it. The passed parameters are $1 , $2 , $3 …
$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script.
In both cases, the -z flag is a parameter to the bash's "test" built-in (a built-in is a command that is built-into the shell, it is not an external command). The -z flag causes test to check whether a string is empty. Returns true if the string is empty, false if it contains something.
You can either return
a result from your function or use $()
to capture its output:
if [ $(foo $arg) -eq 0 ] ; then
Are you sure you need your function to echo 0 or 1? It looks more like you want something like
foo() {
if [ $1 = "zero" ]; then
return 0
else
return 1
fi
}
# Or even just simply foo () { [ $1 = "zero ]; }
arg="zero"
if foo $arg; then
echo "entered 0"
else
echo "entered something else"
fi
arg="blah"
if foo $arg; then
echo "entered 0"
else
echo "entered something else"
fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With