1.1 使用多个命令
[leo@orig-leo ~]$ date;who
2018年 01月 01日 星期一 12:59:36 CST
leo :0 2018-01-01 11:08 (:0)
leo pts/0 2018-01-01 12:39 (:0)
1.2 创建shell脚本文件
创建shell脚本文件时,必须在第一行指定要使用的shell,格式为:
#!/bin/bash
#符号用作注释,shell不会处理注释的内容。
下面创建一个shell脚本文件
[leo@orig-leo shell]$ touch test1
[leo@orig-leo shell]$ vi test1
#!/bin/bash
#This script displays the date and who's logged on
echo -n 'The time and date are: '
date
echo "Let's see who's logged into the system"
who
运行脚本shell文件 test1,如果没有权限就赋予权限chmod u+x test1
[leo@orig-leo shell]$ ./test1
The time and date are: 2018年 01月 01日 星期一 15:52:20 CST
Let's see who's logged into the system
leo :0 2018-01-01 11:08 (:0)
leo pts/0 2018-01-01 12:39 (:0)
1.3 使用变量
环境变量
[leo@orig-leo shell]$ vi test2
#!/bin/bash
#display user information from the system.
echo "User info for userid: $USER"
echo UID: $UID
echo HOME: $HOME
[leo@orig-leo shell]$ ./test2
User info for userid: leo
UID: 1000
HOME: /home/leo
用户变量(局部变量):由用户自定义的变量,在整个脚本中使用。由任何字母、数字或下划线组成,区分大小写。通过$符号引用。
[leo@orig-leo shell]$ vi test3
#!/bin/bash
#testing variables
days=10
guest="Tom"
echo "$guest checked in $days days ago"
days=5
guest="Jee"
echo "$guest checked in $days days ago"
[leo@orig-leo shell]$ chmod u+x test3
[leo@orig-leo shell]$ ./test3
Tom checked in 10 days ago
Jee checked in 5 days ago
变量赋值
[leo@orig-leo shell]$ vi test4
#!/bin/bash
#assigning a variable value to another variable
value1=10
value2=$value1
echo The resulting value is $value2
echo The resulting value is value2
[leo@orig-leo shell]$ chmod u+x test4
[leo@orig-leo shell]$ ./test4
The resulting value is 10
The resulting value is value2
命令替换:允许将shell命令输出赋给变量
[leo@orig-leo shell]$ vi test5
#!/bin/bash
test1=`date`
test2=$(date)
echo "The date and time are: $test1"
echo "The date and time are: $test2"
[leo@orig-leo shell]$ chmod u+x test5
[leo@orig-leo shell]$ ./test5
The date and time are: 2018年 01月 02日 星期二 20:25:56 CST
The date and time are: 2018年 01月 02日 星期二 20:25:56 CST