shell脚本中变量的定义方法
环境级别
export a = 1
在环境关闭后变量失效
用户级别
vim ~/ .bash_profileexport a = 1
系统级别
vim / etc / profileexport a = 2vim / etc / profile.d / westos.shexport b = 3
变量名称规则
####
变量名称可包含的字符
字母
下划线
_
数字
####
变量名称定义规则
不能用数字开头
####
建议
:
变量名称短全用大写字符
变量名称长用
_
区分子类
WESTOS
Westos_Linux
westoS_Linux
变量的转译
#
1
)
转译
\ | 转译单个字符 |
“” | 弱引用,批量转译个数字符 不能转译"\ " "" "$" "!" |
’‘ | 强引用 |
#
2
)
声明
a = 1echo ${a}b
#
3
)
变量的数组
a = ( 1 2 3 4 5 )a$[a[ @ ] : 起始元素 id : 元素个数 ]echo ${a[ 0 ]} ## 数组中第一个元素echo ${a[ 1 ]} ## 数组中最后一个元素echo ${a[ * ]} ## 数组中所有元素echo ${a[ @ ]} ## 数组中所有元素echo ${a[ @ ] : 0 : 3 } ## 数组中 13 个元素echo ${#a[ @ ]} ## 数组中元素的个数unset a[n] ## 删除数组中的第 n1 个元素unset a ##删除 a 这个数组
Linux中命令的别名设定
alias xie = 'vim'
##
临时设定
vim ~/ .bashrcalias xie = 'vim'
##
只针对与用户生效
vim / etc / bashrc ## 针对系统所以用户生效alias xie = 'vim'
unalias xie ## 删除当前环境中的 alias
用户环境变量的更改
设定方式
:
~/ .bash_profileexport PATH = $PATH :/ mnt
/ etc / bash_profileexport PATH = $PATH :/ mnt
#
1
)
直接利用命令执行结果
$()| | 优先执行 |
TEST=hostname
TEST=$(hostname)
#
2
)
脚本中的传参
非交互模式
:
$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赋值 |
read -p "please input word:" | 输出提示语 |
read -p "please input word:" -s | 隐藏输入内容 |
脚本函数
定义
:
程序的别名
设定方式
:
WORD(){action1action2}
WORD
在脚本中就代表
action1 action2
这两个动作
练习脚本
sh create_user.sh
Please input username
:
westos
westos exist
<
output
>>
westos is exist
>
Please input username
:
westos not existplease input password
:
无回显密码
此用户会自动建立并且密码为提示后设定的密码
并显示
:
westos is created
并再次提示
Please input username
:
当
Please input username
:
exit
![](https://img-blog.csdnimg.cn/direct/f1e6600a1b9e447990661b4a98dd0e80.png)