书写脚本的要求:
- 脚本第一行要求使用 shebang(#!) 符号指定一个脚本的解释器,如 #!/bin/bash、#!/bin/sh、#!/usr/bin/env python等脚本文件使用 # 或 << 符号实现单行或多行注释,被注释的关键词或代码将不被执行,如记录脚本功能、版本、作者联系方式等。脚本内容是从上往下顺序执行,一行是一条命令。
[root@localhost jiaofan]# vi a.sh [root@localhost jiaofan]# sh a.sh hello world [root@localhost jiaofan]# cat a.sh #!/bin/bash <注:<<符号后面的关键词可以使任意字符串,但是前面使用什么关键词,结束注释时必须使用相同的关键词。如果从< 二、脚本执行方式(4种方式)
1、脚本文件自身没有可执行权限
默认情况下,脚本是没有执行权限的,无法直接执行,但是 bash 或者 sh 这样的解释器,可以将脚本文件作为参数(读取脚本文件中的内容)来执行脚本
[root@localhost jiaofan]# ./a.sh -bash: ./a.sh: 权限不够 [root@localhost jiaofan]# ll a.sh -rw-r--r--. 1 root root 98 2月 8 15:10 a.sh [root@localhost jiaofan]# sh a.sh hello world [root@localhost jiaofan]# bash a.sh hello world2、脚本文件具有可执行权限
[root@localhost jiaofan]# chmod +x a.sh #<==增加可执行权限 [root@localhost jiaofan]# ./a.sh #<==相对路径执行 hello world [root@localhost jiaofan]# /root/jiaofan/a.sh #<==绝对路径执行 hello world3、开启子进程执行的方式
[root@localhost jiaofan]# ./a.sh hello world [root@localhost jiaofan]# sh a.sh hello world [root@localhost jiaofan]# bash a.sh hello world4、不开启子进程的执行方式(即当前进程)
[root@localhost jiaofan]# . a.sh hello world [root@localhost jiaofan]# source a.sh hello world5、开启子进程和不开启子进程的区别
可以理解为,当前终端是一个进程,如果不开启子进程执行exit,就等于在当前终端输入exit。如果开启子进程,等于另外开了一个进程,然后退出另外一个进程,对父进程没有影响。下面是案例:
[root@localhost jiaofan]# cat a.sh #!/bin/bash exit [root@localhost jiaofan]# bash a.sh #<==开启子进程 [root@localhost jiaofan]# [root@localhost jiaofan]# source a.sh #<==不开启子进程 Connection closed by foreign host. Disconnected from remote host(159) at 15:51:48. Type `help' to learn how to use Xshell prompt. [c:~]$ #<==直接退出三、在脚本中实现数据的输入和输出1、输出:echo
echo [ 选项 ] 字符串 [ 选项 ] -n:不换行,默认echo换行,可以指定-n参数不换行 -e :可以让 echo 命令识别后面的转移符号含义。转义符好如下图
符号 功能描述 b 退格键(Backspace)左移一位 f 换行但光标扔留在原来的位置 n 换行且光标移至行首 r 光标移至行首,但不换行 t 插入Tab键 打印


