1. 程式人生 > >《shell編程實戰》第2章shell腳本入門(下)

《shell編程實戰》第2章shell腳本入門(下)

shell 老男孩 腳本

1、sh和./的區別
[root@thzzc1994 ~]# cat test.sh
echo I am thzzc1994
[root@thzzc1994 ~]# sh test.sh
I am thzzc1994
[root@thzzc1994 ~]# bash test.sh
I am thzzc1994
[root@thzzc1994 ~]# ./test.sh
-bash: ./test.sh: 權限不夠
想要讓./可以執行,需要在用戶位加權限x(可執行exec的意思),
在我的環境下執行chmod u+x test.sh等價於chmod 744 test.sh:
[root@thzzc1994 ~]# ll test.sh
-rw-r--r-- 1 root root 20 4月 22 11:45 test.sh
[root@thzzc1994 ~]# chmod u+x test.sh(chmod 744 test.sh)
[root@thzzc1994 ~]# ll test.sh
-rwxr--r-- 1 root root 20 4月 22 11:45 test.sh
[root@thzzc1994 ~]# ./test.sh
I am thzzc1994
提示:由於./方法每次都需要給定執行權限,但容易被忘記,且多了一些步驟,增加了復雜性,所以一般都是用sh執行。
2、sh和source的區別
[root@thzzc1994 ~]# echo ‘userdir=pwd
‘>test.sh
[root@thzzc1994 ~]# cat test.sh
userdir=pwd
[root@thzzc1994 ~]# sh test.sh
[root@thzzc1994 ~]# echo $userdir

在當前shell查看userdir的值,發現值是空的。現在以同樣的步驟改用source來執行,再來看看userdir變量的值:
[root@thzzc1994 ~]# source test.sh
[root@thzzc1994 ~]# echo $userdir
/root
結論:通過source或.加載執行過的的腳本,由於是在當前shell中執行腳本,因此在腳本結束之後,腳本中的變量(包括函數)值在當前shell中依然存在,而sh和bash執行腳本都會啟動新的子shell執行,執行完後回到父shell,變量和函數值無法保留。

平時在進行shell腳本開發時,如果腳本中有引用或執行其他腳本的內容或配置文件的需求時,最好用.或source先加載該腳本或配置文件,再加載腳本的下文。
趁熱打鐵:這是某互聯網公司linux運維職位筆試題。請問echo $user的返回結果為()
[root@thzzc1994 ~]# cat test.sh
user=whoami
[root@thzzc1994 ~]# sh test.sh
[root@thzzc1994 ~]# echo $user
(A)當前用戶
(B)thzzc1994
(C)空值
前面已經講過了,sh的變量值,父shell是得不到的。所以這題可以看成只有一句話,那就是
[root@thzzc1994 ~]# echo $user
結果當然是空值了。
結論:(1)子shell腳本會直接繼承父shell的變量、函數等,就好像兒子隨父親姓,基因繼承父親的,反之則不可以。
(2)如果希望父shell繼承子shell,就先用source或.加載子shell腳本,後面父shell就能用子shell的變量和函數值了。
3、介紹一個簡單編輯腳本命令cat>,能大大方便開發
cat>test.sh,輸入內容後按回車,再按Ctrl+d組合鍵結束編輯。
[root@thzzc1994 ~]# cat>test.sh
echo I am thzzc1994 [Enter][Ctrl+d]
[root@thzzc1994 ~]# sh test.sh
I am thzzc1994

《shell編程實戰》第2章shell腳本入門(下)