Shell基本學習(4)---腳本

1.註釋

井號後面的不會執行
[root@localhost ~]# #123
[root@localhost ~]#

2.函數

語法:[function] 函數名()

{

內容

}

調用 函數名

[root@localhost ~]# test_out()
> {
> echo "我執行了"
> }
[root@localhost ~]# test_out
我執行了

3.函數傳參

函數定義:$1 $2 ...爲參數佔位,最多9個

[root@localhost ~]# print_args()
> {
> echo $2...$1
> }
[root@localhost ~]# print_args 我是第一個參數 我是第二個參數
我是第二個參數...我是第一個參數

4.return返回值,返回值會存儲到$?中

[root@localhost ~]# funWithReturn(){
> echo "第一個數字:"
> read one
> echo "第二個數字"
> read sec
> echo "數字分別$one和$sec"
> return $(($one+$sec))
> }
[root@localhost ~]# funWithReturn
第一個數字:
1
第二個數字
2
數字分別2和4
[root@localhost ~]# num=$?
[root@localhost ~]# echo $num
6

5.執行自定義.sh文件

建立個xxx.sh文件寫入要執行的語句
例如:top | grep sys
後進行執行
[root@localhost ~]# sh foot.sh 
     1 root      20   0  128164   6808   4044 S   0.0  0.4   0:01.43 systemd                                                        
方法2                                                       
[root@localhost ~]# bash foot.sh  
方法3
[root@localhost ~]# ./foot.sh
-bash: ./foot.sh: Permission denied  (權限不夠,可執行命令都需要賦權)
賦予權限
chmod+x foot.sh
執行
[root@localhost ~]# ./foot.sh        
     1 root      20   0  128164   6808   4044 S   0.0  0.4   0:01.43 systemd                                                        
     1 root      20   0  128164   6808   4044 S   0.0  0.4   0:01.43 systemd   

6.腳本傳參

腳本文件
echo $1
top | grep $2
執行腳本
[root@localhost ~]# sh foot.sh 開始執行過濾 sys
開始執行過濾
     1 root      20   0  128164   6808   4044 S   0.0  0.4   0:01.43 systemd                                                        
     1 root      20   0  128164   6808   4044 S   0.0  0.4   0:01.43 systemd   

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章