bash变量类型:
环境变量
本地变量(局部变量)
位置变量
特殊变量
本地变量:
set VARNAME=VALUE: 作用域为整个bash进程;
局部变量:
local VARNAME=VALUE:作用域为当前代码段;
环境变量:作用域为当前shell进程及其子进程;(操作变量本身使用VARNAME,操作变量的值则只用$VARNAME)
export VARNAME=VALUE
VARNAME=VALUE
export VARNAME
“导出”
[[email protected] ~]# export name
[[email protected] ~]# bash
[[email protected] ~]# echo $name
cxiong
[[email protected] ~]# bash
[[email protected] ~]# echo $name
cxiong
引用变量:${VARNAME},括号有时可以省略
[[email protected] ~]# name=cxiong
[[email protected] ~]# echo $name
cxiong
[[email protected] ~]#
[[email protected] ~]# echo "my name is $name"
my name is cxiong
[[email protected] ~]#
位置变量:
$1, $2, ...
特殊变量:
$?: 上一个命令的执行状态返回值;
[[email protected] ~]# echo $?
0
[[email protected] ~]# ll /varr
ls: cannot access /varr: No such file or directory
[[email protected] ~]# echo $?
2
[[email protected] ~]#
程序执行,可能有两类返回值:
程序执行结果
程序状态返回代码(0-255)
0: 正确执行
1-255:错误执行,1,2,127系统预留;
输出重定向:
>
>>
2>
2>>
&>
撤消变量:
unset VARNAME
[[email protected] ~]# unset name
[[email protected] ~]# echo $name
[[email protected] ~]#
查看当shell中变量:
set
[[email protected] ~]# set
BASH=/bin/bash
BASHOPTS=checkwinsize:cmdhist:expand_aliases:extquote:force_fignore:hostcomplete:interactive_comments:login_shell:progcomp:promptvars:sourcepath
BASH_ALIASES=()
BASH_ARGC=()
BASH_ARGV=()
BASH_CMDS=()
查看当前shell中的环境变量:
printenv
env
export
脚本:命令的堆砌,按实际需要,结合命令流程控制机制实现的源程序
shebang: 魔数
#!/bin/bash
# 注释行,不执行
内核只能执行ELF类型
[[email protected] ~]# nano first.sh
[[email protected] ~]# ll first.sh
[[email protected] ~]# chmod +x first.sh
[[email protected] ~]# pwd
[[email protected] ~]# first.sh
#
# /etc/fstab
# Created by anaconda on Sun Jun 21 02:15:00 2015
#
# Accessible filesystems, by reference, are maintained under ‘/dev/disk‘
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/null: 软件设备, bit bucket,数据黑洞
$?
[[email protected] ~]# id student &> /dev/null
[[email protected] ~]# echo $?
1
[[email protected] ~]# id rhel &> /dev/null
[[email protected] ~]# echo $?
0
[[email protected] ~]#
脚本在执行时会启动一个子shell进程;
命令行中启动的脚本会继承当前shell环境变量;
系统自动执行的脚本(非命令行启动)就需要自我定义需要各环境变量;