Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments to a function within an if statement in bash

Tags:

bash

shell

unix

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
like image 909
user1117603 Avatar asked Feb 17 '13 09:02

user1117603


People also ask

How do you pass an argument to a function in bash?

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 …

What does [- Z $1 mean in bash?

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

What is if [- Z in bash?

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.


2 Answers

You can either return a result from your function or use $() to capture its output:

if [ $(foo $arg) -eq 0 ] ; then
like image 163
cnicutar Avatar answered Oct 11 '22 07:10

cnicutar


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
like image 26
chepner Avatar answered Oct 11 '22 07:10

chepner