本地有两个文件: arg.txt 和 about.sh。
目标是把arg.txt里的内容输出,并作为about.sh的输入。
先看arg.txt里存的是什么:
[liusiyi@localhost ~]$ cat arg.txt
Bob
Ella
Justin
Christin
Steven
Olivia
再看 about.sh里存的是什么(其实是一段对Shell特殊变量的解释,包括 $0, $#, $*, $@, $?, $$):
[liusiyi@localhost ~]$ cat about.sh
#!/bin/bash echo "File name, \$0: $0" echo "First argument, \$1: $1" echo "Second argument, \$2: $2" echo "Quated values, \$*: $*" echo "Quated values, \$@: $@" echo "Shell Id, \$$: $$" echo "Return value (success 0, fail 1), \$?: $?" echo "Total # of arguments, \$#: $#" echo -e "\nSee differences about \$*, \$@, \"\$*\", and \"\$@\" as below:" echo "---- print each argument from \$* ----" count=0 for var in $* do count=$((count+1)) echo "$var" done echo "(totally $count)" echo "---- print each argument from \$@ ----" count=0 for var in $@ do count=$((count+1)) echo "$var" done echo "(totally $count)" echo "---- print each argument from \"\$*\" ----" count=0 for var in "$*" do count=$((count+1)) echo "$var" done echo "(totally $count)" echo "---- print each argument from \"\$@\" ----" count=0 for var in "$@" do count=$((count+1)) echo "$var" done echo "(totally $count)" echo "----------------end--------------"
步骤一,把arg.txt的内容传给变量a:
[liusiyi@localhost ~]$ a=$(cat arg.txt)
步骤二,查看变量a的值:
[liusiyi@localhost ~]$ echo $a Bob Ella Justin Christin Steven Olivia
步骤三,变量a的值被about.sh调用,显示了$0, $#, $*, $@, $?, $$,以及"$*", "$@"在这个命令中的真实值:
[liusiyi@localhost ~]$ about.sh $a
File name, $0: ./about.sh First argument, $1: Bob Second argument, $2: Ella Quated values, $*: Bob Ella Justin Christin Steven Olivia Quated values, $@: Bob Ella Justin Christin Steven Olivia Shell Id, $$: 25985 Return value (success 0, fail 1), $?: 0 Total # of arguments, $#: 6 See differences about $*, $@, "$*", and "$@" as below: ---- print each argument from $* ---- Bob Ella Justin Christin Steven Olivia (totally 6) ---- print each argument from $@ ---- Bob Ella Justin Christin Steven Olivia (totally 6) ---- print each argument from "$*" ---- Bob Ella Justin Christin Steven Olivia (totally 1) ---- print each argument from "$@" ---- Bob Ella Justin Christin Steven Olivia (totally 6) ----------------end--------------
注意,被双引号包含时,"$*" 的参数被当做一个整体,所以遍历里面的元素之后 totally count=1;而 "$@" 依旧是遍历每一个参数,所以count=6
以上步骤也可以简写为:
[liusiyi@localhost ~]$ about.sh $(cat arg.txt)