說明
- GitHub地址:https://github.com/ouyangsuo/SimpleShellDemos
- 以下外殼腳本,完成後全部拷貝至系統的公共可執行程序目錄,使得可以在任意目錄下執行
sudo cp hello calc mcp fileinfo guessnum /bin/
HelloShell(/ bin中/你好)
#!/bin/bash
#↑聲明shell解釋器位置
word="Hello Shell"
echo "Hello Shell!"
數學計算(/ bin中/計算值)
#!/bin/bash
# calc --add 3 4 執行結果爲7
#第一個參數爲--add時,做加法
if [[ $1 = "--add" ]];then
echo --add
echo $(($2+$3))
#第一個參數爲--sub時,做減法
elif [[ $1 = "--sub" ]];then
echo --sub
echo $(($2-$3))
#第一個參數爲--mul時,做乘法
elif [[ $1 = "--mul" ]];then
echo --mul
echo $(($2*$3))
#第一個參數爲--div時,做除法
elif [[ $1 = "--div" ]];then
echo --div
echo $(($2/$3))
#第一個參數爲--div時,做求餘
elif [[ $1 = "--mod" ]];then
echo --mod
echo $(($2%$3))
#第一個參數爲其它時,提示錯誤
else
echo $1
echo fuck off,不支持的操作符
fi
顯示文件信息(/ bin中/ FileInfo的)
#!/bin/bash
#fileinfo ~/hello 顯示該文件的權限和內容
fileinfo(){
# 如果文件不存在,報錯退出
if [[ ! -e $1 ]];then
echo "$1 doesn't exist!"
return 0
fi
echo $1:
#判斷和輸出文件的讀寫執行權限
if [[ -r $1 ]];then
echo -n "readable,"
else
echo -n "NOT-readble,"
fi
if [[ -w $1 ]];then
echo -n "writable,"
else
echo -n "NOT-writable,"
fi
if [[ -x $1 ]];then
echo "executable"
else
echo "NOT-executable"
fi
#通過Linux的標準命令,輸出文件內容
echo -e "\ncontents":
echo ====================
cat $1
echo ====================
}
# 調用函數,傳入文件位置參數
fileinfo $1
自定義的文件拷貝(/ bin中/ MCP)
#!/bin/bash
#用戶通過mcp srcfile dstfile實現拷貝
#通過mcp -a srcfile dstfile實現追加
#拷貝完成後詢問用戶是否立即查看
docp(){
#判斷是新建還是追加
append=0
if [[ $1 = "-a" ]];then
append=1
srcfile=$2
dstfile=$3
else
append=0
srcfile=$1
dstfile=$2
fi
echo "srcfile:$srcfile,dstfile:$dstfile"
#判斷源文件是否存在
if [[ ! -e $srcfile ]];then
echo "stupid! souce file does not exist!"
return 0
fi
#如果目標文件不存在則創建
if [[ ! -e $dstfile ]];then
touch $dstfile
fi
#寫入文件
if [[ $append -eq 1 ]];then
cat < $srcfile >> $dstfile
else
cat < $srcfile > $dstfile
fi
#詢問用戶是否要查看目標文件
echo -n "$srcfile written to $dstfile successfully! read it now?[y/n]:"
read temp
if [[ $temp = 'y' ]];then
echo "content:"
echo ====================
cat < $dstfile
echo ====================
fi
}
#調用函數,傳入參數
docp $1 $2 $3
猜數字小遊戲(/ bin中/ guessnum)
#!/bin/bash
#生成隨機數,此處的rand命令需要安裝一下
answer=`rand --max 1000`
#answer=$(cat /dev/urandom | head -n 10 | cksum | awk -F ' ' '{print $1}')
#answer=$(($answer%1000))
echo $answer
while true
do
#提示用戶輸入
echo -n "please enter a num between 0~1000:"
read guess
#看答案
if [[ $guess = "drop it" ]];then
echo "the answer is:$answer"
break
fi
#對比
if [[ $guess -eq $answer ]];then
echo "bingo!the answer is:$answer"
break
elif [[ $guess -gt $answer ]];then
echo "too big!"
else
echo "too small!"
fi
done
echo "GAME OVER!"