Shell脚本 ---执行脚本前,权限最好chmod a+x filename

来源:互联网 发布:杨浦区人口普查数据 编辑:程序博客网 时间:2024/06/03 12:44

[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]#