linux基礎之Shell Script
1 Shell Scipt
使用指令和基本程序設計結構寫成的程序,可以完成復雜的處理流程
1.1 程序書寫
代碼如下:
#!/bin/bash
# Program:
# This program shows "Hello Wrold" in your screen.
# History:
# 2013/2/3 on_1y First release
PATH=$PATH
export PATH
echo -e "Hello World!/a/n"
exit 0
第一行 #!/bin/bash 說明使用的shell類型,不同shell語法可能不同,所以要說明使用的是哪種shell
其它#開始的表示注釋,注釋一般需要說明
程序功能
版本歷史
作者及聯系方式
設置好PATH變量,以便直接可以調用相應路徑下的命令
程序主體部分
exit 0 表示程序執行成功,向環境返回0
1.2 程序執行
bash $bash sh01.sh #如果用sh sh01.sh而sh又不是指向bash,那么sh01.sh內的語法就會不一致,因為用 #sh去解釋了bash語法寫的shell script,針對這個程序,如果 #$type sh #得到sh is hashed (/bin/sh) #那么會輸出-e Hello world!,而非Hello world!
代碼如下:
$./xxx.sh $chmod +x sh01.sh $./sh01.sh
source $ source sh01.sh
注:用bash和用source的不同在于,用bash執行時,shell script其實是在在父程序bash下新建了一個 bash子程序,這個子程序中執行,當程序執行完后,shell script里定義的變量都會隨子程序的結束而消失, 而用source執行時,是在父程序bash中執行,shell script里定義的變量都還在。
2 簡單Shell練習
2.1 例1 接收用戶輸入
代碼如下:
# !/bin/bash
# Program:
# This program is used to read user's input
# Site: www.jb51.net
# 2013/2/3 on_1y First release
PATH=$PATH
export PATH
read -p "Your first name:" firstname # tell user to input
read -p "Your last name:" lastname # tell user to input
echo -e "/nYour full name: $firstname $lastname"
exit 0
調用:
代碼如下:
$ bash sh02.sh
Your first name:Minix
Your last name:007
Your full name: Minix 007
2.2 例2 按日期建立相似名字的文件
代碼如下:
# !/bin/bash
# Program:
# This program is used to create files according to date
# History:
# 2013/2/3 on_1y First release
PATH=$PATH
export PATH
# Get filename from user
echo -e "I will use 'touch' to create three files."
read -p "Please input your filename:" tmpfilename
# Prevent the user input [Enter]
# Check whether filename exists or not
filename=${tmpfilename:-"filename"}
# Get the final filename according to date
date1=$(date --date='2 days ago' +%Y%m%d) # date of 2 days ago
date2=$(date --date='1 days ago' +%Y%m%d) # date of yesterday
date3=$(date +%Y%m%d) # date of today
filename1=${filename}${date1}
filename2=${filename}${date2}
filename3=${filename}${date3}
# Create file
touch "$filename1"
新聞熱點
疑難解答