1. 程式人生 > >Shell指令碼 ---執行指令碼前,許可權最好chmod a+x filename

Shell指令碼 ---執行指令碼前,許可權最好chmod a+x filename

[root@localhost ~]# echo $(( 13 % 3 ))
1

#註釋:這個有沒有空格是關鍵!!

互動式指令碼:變數內容由使用者決定

[root@localhost ~]# vi sh02.sh 

1 #!/bin/bash
2 # Program:
3 # User inputs his first name and last name. Program shows his full name.
4 # History:
5 PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
6 export PATH
7 read -p "Please input your first name : " firstname
8 read -p "Please input your last name : " lastname
9 echo -e "\nYour full name is :$firstname $lastname "

[root@localhost ~]# sh sh02.sh
Please input your first name : Gao
Please input your last name : Zhenan

Your full name is :Gao Zhenan


隨日期變化:利用日期進行檔案的建立:

[root@localhost shelldemo]# cat sh03.sh
#!/bin/bash
#Program:
# creates three files ,which named by user's input
# and date command.
# History :
# 2013/06/10
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
#1、讓使用者輸入檔名,並取得fileuser這個變數;
echo -e "I will use 'touch' command to create 3 files."
read -p "Please input your filename: " fileuser
#2、為了避免使用者隨意按【enter】,利用變數功能分析檔名是否有設定
filename=${fileuser:-"filename"}
# 3、開始利用date 命令來取得所需要的檔名了。
date1=$(date --date='2 days ago' +%Y%m%d)
date2=$(date --date='1 days ago' +%Y%m%d)
date3=$(date +%Y%m%d)
file1=${filename}${date1}
file2=${filename}${date2}
file3=${filename}${date3}
#4、建立檔名
touch "$file1"
touch "$file2"
touch "$file3"

執行結果:

[root@localhost shelldemo]# date
2013年 05月 04日 星期六 07:37:54 CST

[root@localhost shelldemo]# sh sh03.sh
I will use 'touch' command to create 3 files.
Please input your filename: file
[root@localhost shelldemo]# ll
總計 8
-rw-r--r-- 1 root root 0 05-04 07:39 file20130502
-rw-r--r-- 1 root root 0 05-04 07:39 file20130503
-rw-r--r-- 1 root root 0 05-04 07:39 file20130504
[root@localhost shelldemo]#

數值運算:簡單的加減乘除

[root@localhost shelldemo]# vi sh04.sh

1 #!/bin/bash
2 # Program
3 # User inputs 2 integer numbers;program will cross these two numbers.
4 PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
5 export PATH
6 echo -e "You should input 2 numbers. I will cross them! \n"
7 read -p "first number: " firstnu
8 read -p "second number: " secnu
9 total=$(( $firstnu*$secnu ))
10 echo -e "\nThe result of $firstnu x $secnu is ==> $total"

執行結果:

[root@localhost shelldemo]# sh sh04.sh
You should input 2 numbers. I will cross them!

first number: 23
second number: 2

The result of 23 x 2 is ==> 46
[root@localhost shelldemo]#