我做一些bash脚本,现在我有一个变量调用源和一个数组称为样本,像这样:
source='country'
samples=(US Canada Mexico...)
因为我想要扩展源的数量(每个源都有自己的样本),我尝试添加一些参数来做到这一点。我试了一下:
source=""
samples=("")
if [ $1="country" ]; then
source="country"
samples="US Canada Mexico..."
else
echo "try again"
fi
但是当我运行我的脚本时,它不起作用。
我做错了什么?
您可以在bash中使用“=”或“==”操作符进行字符串比较。重要的因素是括号内的间距。正确的方法是括号内包含空格,运算符周围包含空格。在某些情况下,不同的组合起作用;然而,下面是一个通用的例子。
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).
您可以在bash中使用“=”或“==”操作符进行字符串比较。重要的因素是括号内的间距。正确的方法是括号内包含空格,运算符周围包含空格。在某些情况下,不同的组合起作用;然而,下面是一个通用的例子。
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).
似乎您希望将命令行参数解析到bash脚本中。最近我自己也搜索了一下。我发现了以下内容,我认为可以帮助你分析这些论点:
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 -t test -r server -p password -v .使用实例