您的位置:首页 > 运维架构 > Shell

连载shell(一): 交互式脚本,随日期变化,数值运算

2016-05-29 19:04 537 查看
1.交互式脚本:变量内容由用户决定

需求:

用户输入first name 与last name ,最后在屏幕显示“Your full name is: ”的内容。

debian@debian-pc:~/scripts$ vim sh02.sh

#!/bin/bash
read -p "Please input your first name: " firstname #提示用户输入
read -p "Please input your last name: " lastname #提示用户输入
echo -e "\nYour full name is: $firstname $lastname" #结果由屏幕输出


debian@debian-pc:~/scripts$ sudo chmod a+x sh02.sh
debian@debian-pc:~/scripts$ ./sh02.sh
Please input your first name: mumu
Please input your last name: xizi

Your full name is: mumu xizi


2.随日期变化:利用日期进行文件的创建

需求:

假设我需要创建三个空文件(通过touch),文件最开头由用户输入决定,假设用户输入filename好了,且今天日期为20160529,我想要以前天、昨天、今天的日期来创建这些文件,即filename_20160527, filename_20160528,filename_20160529。

1 #!/bin/bash
2 # Program:
3 #       Program creates three files, which named by user's input and date command.

8
9 #1.让用户输入文件名,并取得fileuser这个变量:
10 echo -e "I will use 'touch' command to creates 3 files." #纯粹显示信息
11 read -p "Please input your filename: " fileuser  #提示用户输入
12
13 #2.为了避免用户随意按【Enter】,利用变量功能分析文件名是否有设置:
14 filename=${fileuser:-"filename"}  #开始判断有否配置文件名
15
16 #3.开始利用date命令取得所需的文件名了
17 date1=$(date --date='2 days ago' +%Y%m%d)  #前两天的日期
18 date2=$(date --date='1 days ago' +%Y%m%d)  #前一天的日期
19 date3=$(date +%Y%m%d)                      #今天的日期
20 file1=${filename}${date1}
21 file2=${filename}${date2}
22 file3=${filename}${date3}
23
24 #4.创建文件名:
25 touch "$file1"
26 touch "$file2"
27 touch "$file3"


debian@debian-pc:~/scripts$ sudo chmod a+x sh03.sh
[sudo] debian 的密码:
**************************************************
debian@debian-pc:~/scripts$ ./sh03.sh
I will use 'touch' command to creates 3 files.
Please input your filename:
#不输入任何字符,结果如下:
debian@debian-pc:~/scripts$ ls
filename20160527  filename20160528  filename20160529   sh03.sh
**************************************************
debian@debian-pc:~/scripts$ ./sh03.sh
I will use 'touch' command to creates 3 files.
Please input your filename: cherry
#输入cherry,结果如下:
debian@debian-pc:~/scripts$ ls
cherry20160527  cherry20160529    cherry20160528  sh03.sh
filename20160528  filename20160527  filename20160529


3.数值运算:简单的加减乘除

需求:

用户输入两个变量,然后将两个变量相乘输出。

注:变量只能定义为整数时,才能进行运算。有两种方式:其一,声明declare,“declare -i total=$firstnu*$secnu”;其二,利用“$((计算式))”进行数值运算,如下。

1 #!/bin/bash
2 # Program
3         User input 2 integer numbers; program will cross these two numbers.

8
9 echo -e "You SHOULD input 2 numbers, I will cross them! \n"
10 read -p "first number: " firstnu
11 read -p "second number: " secnu
12 total=$(($firstnu*secnu))
13 echo -e "\nThe result of $firstnu x $secnu is ==> $total"


debian@debian-pc:~/scripts$ sudo chmod a+x sh04.sh
debian@debian-pc:~/scripts$ ./sh04.sh
You SHOULD input 2 numbers, I will cross them!

first number: 5
second number: 6

The result of 5 x 6 is ==> 30
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  shell 脚本