#!/bin/bash
filename: pp_traverse.sh
Usage: pp_traverse.sh [arguments]
echo "The name of this script is: basename $0"
echo "The arguments are: $*"
echo "The number of arguments is: $#"
for i in “$@” ; do echo "$i" ; done
num=1
for i in “$@”; do
echo "The ${num}th argument is: $i"
echo $1
((num++))
done
<<COMMENT
1.首先你的filename和usage不是这个shell脚本的执行语句;
2.你的执行语句为bash pp_traverse.sh a1 b2 c3 d4,表明你传入的参数依次为a1 b2 c3 d4;
3.echo是输出(到控制台)显示的意思;
4.执行 Shell 脚本时,向脚本传递参数,脚本内获取参数的格式为:$n。n 代表一个数字,0为执行脚本的文件名字,1为执行脚本的第一个参数,2为执行脚本的第二个参数,以此类推……;因此第一个echo输出的是:The name of this script is: basename pp_traverse.sh;
5.$*以一个单字符串显示所有向脚本传递的参数,如"$*"在用「"」括起来的情况下就是以"$1 $2 … $n"的形式输出所有参数,相当于只是传入了一个参数;因此第二个echo输出的是The arguments are: a1 b2 c3 d4;
6.$#获取到的是传递到脚本的参数个数,因此输出的就是The number of arguments is: 4;
7.$@与$*相同,但是使用时加引号,并在引号中返回每个参数,如"$@"用「"」括起来的情况下就是以"$1" "$2" … "$n" 的形式输出所有参数,相当于只是传入了n个参数;for语句就是挨个输出(从1开始),而每一个echo默认都会换行,结合4可知输出是:
“a1
b2
c3
d4”
8.最后一个for语句,num会自增,${num}获取到的就是本sh脚本内num变量的值,参考7可知输出结果是:
The 1th argument is: “a1
The 2th argument is: b2
The 3th argument is: c3
The 4th argument is: d4”
9.至于引号问题,新加一个echo $1,可以查看道输出结果是:
heviosr@ubuntu:~/Desktop/shell$ bash pp_traverse.sh a1 b2 c3 d4
pp_traverse.sh: line 2: filename:: command not found
pp_traverse.sh: line 3: Usage:: command not found
The name of this script is: basename pp_traverse.sh
The arguments are: a1 b2 c3 d4
The number of arguments is: 4
“a1
b2
c3
d4”
The 1th argument is: “a1
a1
The 2th argument is: b2
a1
The 3th argument is: c3
a1
The 4th argument is: d4”
a1
COMMENT