Variables Predefined Bash Variables with Arguments

Can someone tell me what the problem is when I want to change the default value of a variable with an argument in Bash? The following code does not 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:)

+3
source share
1 answer

You are missing fifor the first if. But you're really lucky: there is an easier way to do what you do.

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

From man bash:

${parameter:-word}
Use default values. If the parameter is not specified or is zero, the word is replaced. Otherwise, the parameter value will be replaced.

+7

Source: https://habr.com/ru/post/1763205/


All Articles