一、使用多个命令
shell脚本的关键在于输入多个命令并处理每个命令的结果,甚至将一个命令的结果传给另一个命令。
如果想要几个命令一起执行,可以使用分号将其隔开。
[chendajie@CHENDAJIE my_test]$ date ; who
2019年 10月 08日 星期二 09:19:11 CST
chendajie pts/0 2019-10-08 08:42 (172.17.2.69)
chendajie :0 2019-10-08 08:42 (:0)
chendajie pts/1 2019-10-08 08:42 (172.17.2.69)
chendajie pts/2 2019-10-08 08:42 (:0)
二、创建shell脚本文件
此处我使用的是vim编辑器创建shell脚本:
输入以下命令,创建一个名为test1.sh的脚本文件
[root@CHENDAJIE sh.test]# vim test1.sh
进入vim编辑器编辑界面:
输入以下命令
#!/bin/bash #此处为shell脚本规定格式,不可省略
#This shell will show you the date and who's logged on #注释脚本作用
date
who
保存离开,加入执行权限并执行:
[root@CHENDAJIE sh.test]# chmod +x test1.sh
[root@CHENDAJIE sh.test]# ./test1.sh
2019年 10月 08日 星期二 09:33:11 CST
chendajie pts/0 2019-10-08 08:42 (172.17.2.69)
chendajie :0 2019-10-08 08:42 (:0)
chendajie pts/1 2019-10-08 08:42 (172.17.2.69)
chendajie pts/2 2019-10-08 08:42 (:0)
【注意】,如果你的Linux找不到shell脚本的执行路径,可能是PATH路径中不包含shell脚本文件所在路径,解决的方法有以下两个:
1:将shell脚本文件所处的目录添加到PATH环境变量中;
2:在提示符中用绝对或相对路径来引用shell脚本文件
查看PATH包含的路径可使用以下命令:
[root@CHENDAJIE sh.test]# echo $PATH
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/chendajie/.local/bin:/home/chendajie/bin
三、显示消息(echo命令)
大多数shell命令都会产生自己的输出,这些输出会显示在脚本所执行的控制台显示器上。如果想要添加自己的文本命令消息来告诉脚本用户脚本正在做什么,可以通过echo命令来实现。
在echo命令后面加上一个字符串,该命令就能显示出这个文本字符串。默认情况下,不需要使用引号将要显示的文本字符串划定出来。
[root@CHENDAJIE sh.test]# echo This is a test
This is a test
当字符串中出现引号时:
[root@CHENDAJIE sh.test]# echo Let's see if this'll work
Lets see if thisll work
可以看到此时的单引号没显示出来。
echo命令可用单引号或双引号来划定文本字符串。如果在字符中用到了它,你可以使用另一种引号将字符串划定起来:
[root@CHENDAJIE sh.test]# echo "This is a test to see if you're paying attention"
This is a test to see if you're paying attention
[root@CHENDAJIE sh.test]# echo 'Rich says "scripting is easy".'
Rich says "scripting is easy".
可以将echo语句天年到shell脚本中任何需要显示额外信息的地方。
例如:
将echo加入到我们建立的第一个shell脚本中
#!/bin/bash
#This shell will show you the date and who's logged on
echo The time and date are:
date
echo "Let's see who's logged into the system:"
who
执行显示:
[root@CHENDAJIE sh.test]# ./test1.sh
The time and date are:
2019年 10月 08日 星期二 10:15:15 CST
Let's see who's logged into the system:
chendajie pts/0 2019-10-08 08:42 (172.17.2.69)
chendajie :0 2019-10-08 08:42 (:0)
chendajie pts/1 2019-10-08 08:42 (172.17.2.69)
chendajie pts/2 2019-10-08 08:42 (:0)
echo -n:不输出行尾的换行符
#!/bin/bash
#This shell will show you the date and who's logged on
echo -n The time and date are: #注意看此处加了一个-n选项
date
echo "Let's see who's logged into the system:"
who
[root@CHENDAJIE sh.test]# ./test1.sh
The time and date are:2019年 10月 08日 星期二 10:17:06 CST #此处就没有换行输出
Let's see who's logged into the system:
chendajie pts/0 2019-10-08 08:42 (172.17.2.69)
chendajie :0 2019-10-08 08:42 (:0)
chendajie pts/1 2019-10-08 08:42 (172.17.2.69)
chendajie pts/2 2019-10-08 08:42 (:0)