带参数的可怕的预定义Bash变量

Hav*_*vok 3 variables bash overriding arguments

当我想要在Bash中使用参数的变量中的可变默认值时,有人可以指出我的问题是什么吗?以下代码不起作用:

#!/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"
Run Code Online (Sandbox Code Playgroud)

我希望能够做到:

#./script.sh
Var1: defaultvalue1 ; Var2: defaultvalue2
#./script.sh override1
Var1: override1 ; Var2: defaultvalue2
#./script.sh override1 override2
Var1: override1 ; Var2: override2
Run Code Online (Sandbox Code Playgroud)

提前致谢 :)

Joh*_*ica 7

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}
Run Code Online (Sandbox Code Playgroud)

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.