@xtccc
2016-08-08T13:32:56.000000Z
字数 1663
阅读 2344
Shell
参考:
目录:
# test.sh
for var in "$@" ; do
echo "$var"
done
测试一下:
# ./test.sh "a a a" b c d
a a a
b
c
d
"$@"
表示所有的参数,注意$@两边的双引号是必须的,否则:
# ./test.sh "a a a" b c d
a
a
a
b
c
d
实际上,for var in "$@"
与 for var
是等效的,我们把script改一下:
# test.sh
for var; do
echo "$var"
done
测试:
# ./test.sh "a a a" b c d
a a a
b
c
d
参看命令help for
的解释:
# help for
for:for NAME [in WORDS ... ] ; do COMMANDS; done
Execute commands for each member in a list.
Ifin WORDS ...;
is not present, thenin "$@"
is assumed.
# test.sh
for ((i = 1; i < $#; i++)); do
echo ${!i}
done
测试一下:
# ./test.sh "a a a" "this is a \"double quote\"" c
a a a
this is a "double quote"
c
解释:
$#
表示$0
表示文件名,$1
是第一个参数,$2
是第二个参数,。。。 ${!i}
表示第i个参数,这是 Bash indirection feature另一种写法:将输入参数保存为数组
# test.sh
args=("$@") # 将全部的参数作为数组存储
len=${#args[@]} # 数组的长度
echo "args=${args[@]}" # 一次性输出数组的全部内容
echo "len=$len"
for ((i = 0; i < $len; i++)); do
echo "args[$i]=${args[$i]}" # 通过位置来访问数组的各元素
done
测试一下:
# ./test.sh "a a a" b c
args=a a a b c
len=3
args[0]=a a a
args[1]=b
args[2]=c
注意: echo ${args[@]}
输出数组的全部元素,而echo ${args}
只能输出数组的首元素。
如果参数含有空格,例如希望把a a a
作为一个参数,则传参时使用"a a a"
;如果参数含有空格,例如真正的参数内容为this is "double quote"
,则传参时使用"this is \"double quote\""
。
我们依然使用之前的script:
# test.sh
for var in "$@"; do
echo "$var"
done
测试一下:
# ./test.sh "a a a" "this is \"double quote\"" c d
a a a
this is "double quote"
c
d
shift.sh文件
#!/bin/bash
echo "arg0=$0 arg1=$1 arg2=$2 arg3=$3 arg4=$4"
shift
echo "arg0=$0 arg1=$1 arg2=$2 arg3=$3 arg4=$4"
shift
echo "arg0=$0 arg1=$1 arg2=$2 arg3=$3 arg4=$4"
shift
echo "arg0=$0 arg1=$1 arg2=$2 arg3=$3 arg4=$4"
运行结果:
# ./shift.sh 100 200 300 400 500
arg0=./shift.sh arg1=100 arg2=200 arg3=300 arg4=400
arg0=./shift.sh arg1=200 arg2=300 arg3=400 arg4=500
arg0=./shift.sh arg1=300 arg2=400 arg3=500 arg4=
arg0=./shift.sh arg1=400 arg2=500 arg3= arg4=