天天看點

Shell腳本例子示例:位置參數示例:目錄跳轉、執行其他的腳本

要點:

  • 位置參數
  • 表達式運算
  • 條件表達式

示例:位置參數

#! /bin/bash

if [ $# -ne 2 ]; then
	echo "Usage: $0 x y"
	exit 1
fi

sum=`expr $1 + $2`

echo "$1 + $2 = $sum"
exit 0
           

示例:目錄跳轉、執行其他的腳本

假定目前目錄下有兩個子目錄sub和sub2,下面各有一個腳本檔案sub.sh和sub2.sh。目前目錄下有個test.sh腳本,代碼如下:

#!/bin/bash

echo "test.sh"

CURDIR=`pwd`
TARGETDIR="$CURDIR/sub"
cd $TARGETDIR
source sub.sh
cd -
echo returned. `pwd`

cd $CURDIR/sub2
source sub2.sh
cd -

echo DONE!!!
           

sub和sub2子目錄下的腳本内容如下:

#/bin/bash

echo "this is sub."
           

示例的運作結果:

test.sh
this is sub.
/Users/user_name/curdir
returned. /Users/user_name/curdir
this is sub2.
/Users/user_name/curdir
DONE!!!
           

繼續閱讀