shell构建基本脚本(上)

1.1 使用多个命令

[leo@orig-leo ~]$ date;who
20180101日 星期一 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: 20180101日 星期一 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: 20180102日 星期二 20:25:56 CST
The date and time are: 20180102日 星期二 20:25:56 CST
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值