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"
新闻热点
疑难解答