一、Shell脚本基础元素
将一系列经常需要使用的命令,把它存储在一个文件里,shell可以读取这个文件并顺序执 行其中的命令,我们把这样的文件就叫shell脚本。shell脚本按行解释文件里的命令。
基本元素:
1.声明:声明用哪个命令解释器来解释并执行当前脚本文件中的语句,一般写的解释器为 #!/bin/bash
2.命令:可执行语句,实现程序的功能。
3.注释:说明某些代码的功能,通过在代码中增加注释可以提高程序的可读性。
单行注释: # + 注释内容
多行注释::<<BLOCK ...注释内容 BLOCK
4.赋予rx的权限
内部命令echo:
echo 用于终端打印的基本命令,默认情况下,echo 在每次调用后会添加一个换行符
echo命令使用双引号和单引号的区别:
[root@kittod ~]# echo "the current directory is `pwd`"
the current directory is /root
[root@kittod ~]# echo 'the current directory is `pwd`'
the current directory is `pwd`
[root@kittod ~]# echo "hehe;hehe"
hehe;hehe
[root@kittod ~]# echo hehe;hehe
hehe
-bash: hehe: command not found
echo参数选项 | 说明 |
-n | 不换行输出内容 |
-e |
解析转义字符 |
转义字符 | 说明 \n 换行 |
\r | 回车 |
\t | 制表符 |
\b | 退格 |
\v | 纵向制表符 |
#设置字体颜色
[root@kittod ~]# echo -e "\e[1;31m This is red test \e[0m"
This is red test
\e[1;31m 将颜色设置为红色, \e[0m 将颜色重置,使用时只需要更换颜色代码即可
颜色代码
重置 0
黑色 30
红色 31
绿色 32
黄色 33
蓝色 34
洋红 35
青色 36
白色 37
#设置背景颜色
[root@kittod ~]# echo -e "\e[1;42m This is red test bg \e[0m"
This is red test bg
颜色代码
重置 0
黑色 40
红色 41
绿色 42
黄色 43
蓝色 44
洋红 45
青色 46
白色 47
#export设置或者显示环境变量
[root@kittod ~]# mingzi=hehe
[root@kittod ~]# echo $mingzi
hehe
[root@kittod ~]# bash
[root@kittod ~]# echo $mingzi
[root@kittod ~]# exit
exit
[root@kittod ~]# export mingzi
[root@kittod ~]# bash
[root@kittod ~]# echo $mingzi
hehe
read 命令:
read命令可从标准输入读取字符串等信息,传给shell程序内部定义的变量。read 是一个重要的 bash 命令,用于从键盘或标准输入读取文本,我们可以使用 read 命令以交互 形式读取来自用户的输入。其中:-p prompt:设置提示信息 ;-t timeout:设置输入等待时间,单位默认为秒。
二、执行脚本的方法
(1)bash ./filename.sh(产生子进程,再运行,使用当前指定的bash shell去运行) (2)./filename.sh(产生子进程,再运行,使用脚本里面指定的shell去运行。使用该种方式执行需要x 权限)
(3)source ./filename.sh(source命令是一个shell内部命令,其功能是读取指定的shell程序文件,并 且依次执行其中的所有的语句,并没有创建新的子shell进程,所以脚本里面所有创建的变量都会保存到 当前的shell里面)
(4). filename.sh(和source一样,也是使用当前进程执行)
执行shell脚本时,如果使用1和2这种方式执行会在当前的进程下产生一个新的bash子进程,所以子进程 切换到了/tmp目录,当脚本结束,子进程也就结束了,所以当前进程的目录不会发生变化;3和4方式执 行时,不会产生新的进程,所以脚本执行结束后当前的目录会变成/tmp。
[root@localhost test]# echo 'userdir=`pwd`' > test3.sh
[root@localhost test]# cat test3.sh
userdir=`pwd`
(1)[root@localhost test]# bash test3.sh
[root@localhost test]# echo $userdir
[root@localhost test]#
(2)[root@localhost test]# chmod a+rx test3.sh
[root@localhost test]# ./test3.sh
[root@localhost test]# echo $userdir
[root@localhost test]#
(3)[root@localhost test]# source test3.sh
[root@localhost test]# echo $userdir
/test
(4)[root@localhost test]# . test3.sh
[root@localhost test]# echo $userdir
/test