學習 Shell Scripts @ H's 筆記本 :: 隨意窩 Xuite日誌
  • 關鍵字
    1. 沒有新回應!
  • 2006-05-09 13:12 學習 Shell Scripts
    平均分數:0 顆星    投票人數:0
    我要評分:

    http://linux.vbird.org/linux_basic/0340bashshell-scripts.php

    Shell script 的預設變數($0, $1...)

    其實,當我們執行一個 shell script 時,在這個 shell script 裡面就已將幫我們做好一些可用的變數了。 舉例來說,在不久的將來,您就會發現,當我們要啟動一個系統服務時,可能會下達類似這樣的指令:
    [root@linux ~]# /etc/init.d/crond restart
    
    那是啥玩意兒?呵呵!就是『向 /etc/init.d/crond 這個 script 下達 restart 的指令』, 咦!我們不是都使用 read 來讀取使用者輸入的變數內容嗎?為啥我可以直接在 script 後面接上這個參數? 這是因為 shell script 幫我們設定好一些指定的變數了!變數的對應是這樣的:
    
    /path/to/scriptname  opt1  opt2  opt3  opt4  ...
           $0             $1    $2    $3    $4   ...
    
    這樣夠清楚了吧?!執行的檔名為 $0 這個變數,第一個接的參數就是 $1 啊~ 所以,只要我們在 script 裡面善用 $1 的話,就可以很簡單的立即下達某些指令功能了! 好了,來做個例子吧~假設我要執行一個 script ,執行後,該 script 會自動列出自己的檔名, 還有後面接的前三個參數,該如何是好?
    [root@linux scripts]# vi sh07.sh
    #!/bin/bash
    # Program:
    # 	The program will show it's name and first 3 parameters.
    # History:
    # 2005/08/25	VBird	First release
    PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
    export PATH
    
    echo "The script naem is ==> $0"
    [ -n "$1" ] && echo "The 1st paramter is ==> $1" || exit 0
    [ -n "$2" ] && echo "The 2nd paramter is ==> $2" || exit 0
    [ -n "$3" ] && echo "The 3th paramter is ==> $3" || exit 0
    
    這支程式裡面鳥哥加上了一些控制式,亦即利用 && 及 || 來加以判斷 $1 ~ $3 是否存在? 若存在才顯示,若不存在就中斷~執行結果如下:
    [root@linux scripts]# sh sh07.sh theone haha quot
    The script naem is ==> sh07.sh
    The 1st paramter is ==> theone
    The 2nd paramter is ==> haha
    The 3th paramter is ==> quot
    
    H / Xuite日誌 / 回應(0) / 引用(0) / 好文轉寄
    回應