Ale*_*dro 205 bash scripting arguments
我正在做一些bash脚本,现在我有一个变量调用source
和一个数组调用samples
,如下所示:
source='country'
samples=(US Canada Mexico...)
Run Code Online (Sandbox Code Playgroud)
因为我想扩展源的数量(并且每个源都有自己的样本)我试图添加一些参数来做到这一点.我试过这个:
source=""
samples=("")
if [ $1="country" ]; then
source="country"
samples="US Canada Mexico..."
else
echo "try again"
fi
Run Code Online (Sandbox Code Playgroud)
但是当我运行我的脚本时source countries.sh country
它没有用.我究竟做错了什么?
Ale*_*x L 375
不要忘记空格:
source=""
samples=("")
if [ $1 = "country" ]; then
source="country"
samples="US Canada Mexico..."
else
echo "try again"
fi
Run Code Online (Sandbox Code Playgroud)
Vyk*_*yke 171
您可以使用"="或"=="运算符在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)
Run Code Online (Sandbox Code Playgroud)
另外,与单支架相比,注意双支架的处理方式略有不同......
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).
Run Code Online (Sandbox Code Playgroud)
我希望有所帮助!
ion*_*yed 10
您似乎希望将命令行参数解析为bash脚本.我最近自己搜索过这个.我遇到了以下内容,我认为这将有助于您解析参数:
http://rsalveti.wordpress.com/2007/04/03/bash-parsing-arguments-with-getopts/
我在下面添加了片段作为tl;博士
#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
Run Code Online (Sandbox Code Playgroud)
./script.sh -t test -r server -p password -v