什么是shell?
脚本中命令的解释器。
- shell脚本的意义
1、记录命令执行的过程和执行逻辑,以便以后重复执行;
2、脚本可以批量处理主机;
3、脚本可以定时处理主机。
- 如何创建shell脚本
#!/bin/bash ##幻数
##脚本执行的解释器,最优先运行
vim自动添加脚本首部
"map <F4> ms:call WESTOSTITLE()<cr>'s
autocmd BufNewFile *.sh,*.script call WESTOSTITLE()
func WESTOSTITLE()
call append(0,"#########################")
call append(1,"# Author: lee")
call append(2,"# Version: ")
call append(3,"# Create_Time: ")
call append(4,"# Mail: ")
call append(5,"# Info: ")
call append(6,"# ")
call append(7,"#########################")
call append(8,"")
call append(9,"#!/bin/bash")
endfunc
- 如何执行shell脚本
1、手动在环境中开启指定解释器;
sh script.sh
2、直接在当前环境中运行shell中的指令不开启新的shell;
source script.sh
. script.sh
3、开启脚本中指定的shell并使用此shell环境运行脚本中的指令;
chmod +x script.sh
/xxxx/xxxx/script.sh
./script.sh
- 如何对脚本进行调试
sh -x /mnt/westos.sh
+ ##运行指令
不带+ ##命令运行的输出
变量
- 变量的定义
变量就是内存一片区域的地址
变量存在的意义:命令无法操作一直变化的目标;用一串固定的字符来表示不固定的目标可以解决此问题。
- shell脚本中变量的定义方法
1、环境级别
export a=1
在环境关闭后变量失效
2、用户级别
vim ~/.bash_profile
export a=2
3.系统级别
vim /etc/profile
export a=2
vim /etc/profile.d/westos.sh
export b=3
4、变量名称
"字符" "_" "数字"
不能用数字开头
建议:
变量名称短全用大写字符
变量名称长用_区分子类
WESTOS
Westos_Linux
westoS_Linux
- 变量的转译
1、转译
\ #转译单个字符
"" #弱引用,批量转译字符, 不能转译" \ " " ` " " $ " " ! "
'' #强引用
2、声明
a = 1
echo $ab
echo ${a}b
3、变量的数组
a=(1 2 3 4 5 )
echo $ { a[0] }
echo $ { a[-1] }
echo $ { a[*] }
echo $ { a[@] }
4、Linux中命令的别名设定
alias xie='vim' ##临时设定
vim ~/.bashrc
alias xie='vim' ##只针对与用户生效
vim /etc/bashrc ##针对系统所在用户生效
alias xie='vim'
unalias xie ##删除当前环境中的alias
5、用户环境变量的更改
环境变量:
用户在操作系统时使用到的命令搜索路径。
设定方式:
~/.bash_profile
export PATH=$PATH:/mnt
/etc/bash_profile
export PATH=$PATH:/mnt
6、利用命令的执行结果设定变量
- 直接利用命令执行结果
$()|'' ##优先执行
TEST='hostname' TEST=$(hostname)
- 脚本中的传参
非交互模式:
$0 is /mnt/test.sh ##脚本本身
$1 is westos ##脚本后所输入的第一串字符
$2 is linux
$3 is redhat
$* is westos linux redhat ##脚本后所输入的所有字符"westos linux redhat"
$@ is westos linux redhat ##脚本后所输入的所有字符'westos' 'linux' 'redhat'
$# is 3 ##脚本后所输入的字符串个数
交互模式传参:
read WESTOS ##对westos赋值
ending......