Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overrible predefined Bash variables with arguments

Can someone point me out what is the problem when I want to overrible a default value in a variable with an argument in Bash? The following code doesn't work:

#!/bin/bash

VARIABLE1="defaultvalue1"
VARIABLE2="defaultvalue2"

# Check for first argument, if found, overrides VARIABLE1
if [ -n $1 ]; then
    VARIABLE1=$1
fi
# Check for second argument, if found, overrides VARIABLE2
if [ -n $2 ]; then
    VARIABLE2=$2
fi

echo "Var1: $VARIABLE1 ; Var2: $VARIABLE2"

I want to be able to do:

#./script.sh
Var1: defaultvalue1 ; Var2: defaultvalue2
#./script.sh override1
Var1: override1 ; Var2: defaultvalue2
#./script.sh override1 override2
Var1: override1 ; Var2: override2

Thanks in advance :)

like image 985
Havok Avatar asked Dec 12 '25 18:12

Havok


1 Answers

You're missing the fi for the first if. But actually you're in luck: there's an easier way to do what you're doing.

VARIABLE1=${1:-defaultvalue1}
VARIABLE2=${2:-defaultvalue2}

From man bash:

${parameter:-word}
Use Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

like image 190
John Kugelman Avatar answered Dec 15 '25 18:12

John Kugelman