把一個shell命令的輸出作為另一個shell命令的輸入;特殊變量$0, $#, $*, $@, $?, $$,以及"$*", "$@"代表的含義


本地有兩個文件: 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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM