7heViking
7heViking

Reputation: 7577

Using functions and arguments in if statement in a bash script

I am trying to test the return value of multiple function calls while parsing an argument to one of them. I have tried the following but it does not work.

Can you help?

main() {
if prepareEnvironment "$1" &&
    buildInterfaceConfiguration &&
    applyNetworkInterfaceFiles
then
    echo ':D INSTALLATION COMPLETED :D'
    echo ''
else
    echo ''
    echo ':( INSTALLATION FAILED :('
    echo ''
fi
}

prepareEnvironment() {
echo '####################################################################################'
echo 'Preparing environment'
echo '####################################################################################'
echo "num arg: $#"
echo "arg: $1"
echo $1
...

This example just returns an error when trying to execute the functions.

Upvotes: 0

Views: 54

Answers (1)

Socowi
Socowi

Reputation: 27215

First Answer

The subshell $(...) is the problem, just write

if prepareEnvironment "$1" &&
    buildInterfaceConfiguration &&
    applyNetworkInterfaceFiles
then
    ...

Assume prepareEnvironment "$1" would always print some text, then your version with $(...) would be equivalent to ...

if some text &&
    buildInterfaceConfiguration &&
    applyNetworkInterfaceFiles
then
    ...

... no matter the exit status of prepareEnvironment "$1". In this case, some cannot be interpreted as a command by bash, hence the error.

Second Answer

Regarding the missing argument:
I see that you called prepareEnvironment "$1" inside the function main. If you want to use the $1, you have to pass that to the main function first.

Upvotes: 2

Related Questions