bash脚本中变量的默认值

时间:2018-05-05 12:43:54

标签: bash

我想在bash脚本中为变量赋予默认值。

这是脚本:

unamestr=`uname`
if [[ "$unamestr" == 'Linux' ]] || [[ "$unamestr" == 'Darwin' ]]; then
  DEFAULT_LOCATION="/home/$USER/.kaggle/competitions/$1"
elif [[ "$unamestr" == 'CYGWIN' ]] || [[ "$unamestr" == 'MINGW' ]]; then
  DEFAULT_LOCATION="C:\\Users\\$USER\\.kaggle\\competitions\\$1"
fi

kaggle competitions download -c $1
KAGGLE_LOCATION=${2:-DEFAULT_LOCATION}

mv KAGGLE_LOCATION .
mkdir data
mv $1/*.zip data/
mv $1/*.csv data/

cd data/
unzip *.zip
rm *.zip

当我执行echo $DEFAULT_LOCATION时,会出现正确的值。但是当我执行$ KAGGLE_LOCATION并且不输入任何cmd参数时,我得到DEFAULT_LOCATION作为输出而不是实际值。我的代码出了什么问题?

PS:我从未使用过Mac,因此我不确定unix的位置是否与Mac相同。如果不同,请发表评论。

1 个答案:

答案 0 :(得分:1)

您没有扩展变量,请尝试扩展变量,例如“$ KAGGLE_LOCATION”

unamestr=`uname`
if [[ "$unamestr" == 'Linux' ]] || [[ "$unamestr" == 'Darwin' ]]; then
  DEFAULT_LOCATION="/home/$USER/.kaggle/competitions/$1"
elif [[ "$unamestr" == 'CYGWIN' ]] || [[ "$unamestr" == 'MINGW' ]];then
  DEFAULT_LOCATION="C:\\Users\\$USER\\.kaggle\\competitions\\$1"
fi

kaggle competitions download -c $1
KAGGLE_LOCATION=${2:-DEFAULT_LOCATION}

mv "$KAGGLE_LOCATION" .
mkdir data
mv $1/*.zip data/
mv $1/*.csv data/

cd data/
unzip *.zip
rm *.zip