shell的使用

shell脚本的基本写法

1)脚本第一行,魔法字符#!指定解释器【必写】

#!/bin/bash 表示以下内容使用bash解释器解析

注意: 如果直接将解释器路径写死在脚本里,可能在某些系统就会存在找不到解释器的兼容性问题,所以可以使用:#!/bin/env 解释器 #!/bin/env bash

2)脚本第二部分,注释(#号)说明,对脚本的基本信息进行描述【可选】

#!/bin/env bash

# 以下内容是对脚本的基本信息的描述
# Name: 名字
# Desc:描述describe
# Path:存放路径
# Usage:用法
# Update:更新时间

#下面就是脚本的具体内容
commands
...

3)脚本第三部分,脚本要实现的具体代码内容

㈦ shell脚本的执行方法

  • 标准脚本执行方法(建议)
1) 编写人生第一个shell脚本
[root@MissHou shell01]# cat first_shell.sh
#!/bin/env bash

# 以下内容是对脚本的基本信息的描述
# Name: first_shell.sh
# Desc: num1
# Path: /shell01/first_shell.sh
# Usage:/shell01/first_shell.sh
# Update:2019-05-05

echo "hello world"
echo "hello world"
echo "hello world"

2) 脚本增加可执行权限
[root@MissHou shell01]# chmod +x first_shell.sh

3) 标准方式执行脚本
[root@MissHou shell01]# pwd
/shell01
[root@MissHou shell01]# /shell01/first_shell.sh
或者
[root@MissHou shell01]# ./first_shell.sh

注意:标准执行方式脚本必须要有可执行权限。
  • 非标准的执行方法(不建议)
  1. 直接在命令行指定解释器执行
[root@MissHou shell01]# bash first_shell.sh
[root@MissHou shell01]# sh first_shell.sh
[root@MissHou shell01]# bash -x first_shell.sh
+ echo ‘hello world‘
hello world
+ echo ‘hello world‘
hello world
+ echo ‘hello world‘
hello world
----------------
-x:一般用于排错,查看脚本的执行过程
-n:用来查看脚本的语法是否有问题
------------
  1. 使用source命令读取脚本文件,执行文件里的代码
[root@MissHou shell01]# 想 first_shell.sh
hello world
hello world
hello world

小试牛刀:写一个木有灵魂的脚本,要求如下:

  1. 删除/tmp/目录下的所有文件

  2. 然后在/tmp目录里创建3个目录,分别是dir1~dir3

  3. 拷贝/etc/hosts文件到刚创建的dir1目录里

  4. 最后打印"报告首长,任务已于2019-05-05 10:10:10时间完成"内容

    echo "报告首长,任务已于$(date +‘%F %T‘)"

shell的使用

上一篇:PS自动标注,一键切图神器:摹客iDoc for Mac(V2.2.3中文版)


下一篇:beanshell 时间戳转时间日期