bash脚本:如果参数等于这个string,定义一个像这个string的variables

我正在做一些bash脚本,现在我得到了一个variables调用source和一个名为samples数组,如下所示:

 source='country' samples=(US Canada Mexico...) 

因为我想扩大来源的数量(每个来源都有自己的样本),我试图添加一些参数来做到这一点。 我试过这个:

 source="" samples=("") if [ $1="country" ]; then source="country" samples="US Canada Mexico..." else echo "try again" fi 

但是当我运行我的脚本source countries.sh country它没有工作。 我究竟做错了什么?

不要忘记空间:

 source="" samples=("") if [ $1 = "country" ]; then source="country" samples="US Canada Mexico..." else echo "try again" fi 

您可以在bash中使用“=”或“==”运算符进行string比较。 重要的因素是括号内的间距。 正确的方法是括号内包含间距,操作符包含间距。 在某些情况下,不同的组合有效 但是,以下是一个普遍的例子。

 if [ "$1" == "something" ]; then ## GOOD if [ "$1" = "something" ]; then ## GOOD if [ "$1"="something" ]; then ## BAD (operator spacing) if ["$1" == "something"]; then ## BAD (bracket spacing) 

另外,与单个括号相比,注意双括号的处理方式稍有不同。

 if [[ $a == z* ]]; then # True if $a starts with a "z" (pattern matching). if [[ $a == "z*" ]]; then # True if $a is equal to z* (literal matching). if [ $a == z* ]; then # File globbing and word splitting take place. if [ "$a" == "z*" ]; then # True if $a is equal to z* (literal matching). 

我希望有帮助!

看来你正在寻求parsing命令行参数到你的bash脚本。 我最近自己search了这个。 我碰到以下内容,我认为这将帮助你parsing参数:

http://rsalveti.wordpress.com/2007/04/03/bash-parsing-arguments-with-getopts/

我添加了下面的代码片段作为tl; dr

 #using : after a switch variable means it requires some input (ie, t: requires something after t to validate while h requires nothing. while getopts “ht:r:p:v” OPTION do case $OPTION in h) usage exit 1 ;; t) TEST=$OPTARG ;; r) SERVER=$OPTARG ;; p) PASSWD=$OPTARG ;; v) VERBOSE=1 ;; ?) usage exit ;; esac done if [[ -z $TEST ]] || [[ -z $SERVER ]] || [[ -z $PASSWD ]] then usage exit 1 fi 

./script.sh -ttesting-r服务器-p密码-v

乍一看,你正在做一个assignation =在你的if语句而不是比较==基本上你需要做:

 mysource="" samples=("") if [ "$1" == "country" ]; then mysource="country" samples="US Canada Mexico..." else echo "try again" fi 

IE:

 ~$ source /tmp/foo.sh country ~$ echo $samples US Canada Mexico... 

那是你要的吗?