#接受一個參數,並用之創建目錄,然後參數被傳入命令行,重設給變量DIRECTORY,最後測試變量是否為空。
#!/bin/sh
DIRECTORY=$1
if [ "$DIRECTORY" = "" ]
then
echo "Usage:`basename $0` directory to create" >&2
exit 1
fi
if [ -d $DIRECTORY ]
then :
else
echo "The directory not exist"
echo -n "Create it now? [y/n]:"
read ANS
if [ "$ANS" = "y" ] || [ "$ANS" = "Y" ]
then
echo "creating......"
mkdir $DIRECTORY >/dev/null 2>&1
if [ $? != 0 ];
then
echo "Errors creating the directory $DIRECTORY" >&2
exit 1
fi
else :
fi
fi
這裡使用最簡單的嵌套的if else語句。
if 條件
then
命令1
else
命令2
fi
記住,如果沒有命令1或2,需在then或else後面加上空格+:,否則shell程序將報錯。