关于变量
一.系统中变量定义
系统中变量的查看
env 查看当前系统的所有变量
部分省略
环境级的变量设置,退出当前环境无效
export
定义环境变量AA=88,env查看
export AA=88
新建shell查看变量AA是否存在,实验结果是不存在了
用户级变量,切换用户无效
cd ~
ls -a|A
vim .bash_profile
--->>export BB=100
source .bash_profile 当前环境重新读取该文件
切换用户发现变量会不存在了,这是因为这种设置是用户级别的变量设置
全局变量设置(只有root用户有权限)开机重启生效
vim /etc/profile
--->>export CC=123
source /etc/profile
都可以使用该变量了
显示变量PS1
echo $PS1
PS1='定义变量'
二变量名称的规范
变量名称中通常包含大小写字母,数字,下划线(非必须):以下是合法的变量名称
WESTOS_LINUX
Westos_Linux
westoS_Linux
字符的转义和变量的声明
\ 转义单个字符
"" 弱引用,批量转义""中出现的字符
'' 强引用,批量转义''中出现的字符
''与"" 两者的区别在于,""不能转义\,`,!,$
${} 变量声明
例如:
A=1
echo $Ab
echo ${A}b
for i in {1..4}
do
echo $i
done
-------
seq 1 4
两者结果一样
三.变量值的传递
$1 脚本后第一串字符
$2 脚本后第二串字符
$3 脚本后第三串字符
$# 脚本后所有字符的总个数
$* 脚本后所有的字符串;模式为"1 2 3"
$@ 脚本后跟的左右字符串;模式为"1" "2" "3"
read实现变量的传递
read [westos] ##回车后弹出输入框直接输入westos,westos会显示
read -s [westos] ##回车后弹出输入框直接输入westos,westos不显示,隐藏
read -p "input:" ##设置输入框提示信息,输入会显示
read -sp "input:" ##设置输入框提示信息,输入不会显示
#!/bin/bash
read -p "input name:" $1
read -p "input passwd:" $2
利用命令将执行结果设置为函数
将当前时间赋给TODAY
TODAY=`data`
echo $TODAY
$?是命令在执行完成之后产生的退出值,范围【0-255】
当$?=0时表示命令执行没有错误输出,这个值可以用exit命令执行
例如 exit 0
脚本中的函数
脚本中的函数时把一个复杂的语句块定义成一个字符串的方法
Host_Message()
{
read -p "Please input you action: " Action
[ "Action" == "exit" ] && exit 0
[ "Action" == "user"]&&echo You are $USER
[ "Action" == "hostname" ]&& echo $HOST
Host_Message
}
Host_Message
自定义命令:
以vim为例
环境级
alias xie=‘vim‘
用户级
vim /root/.bashrc
alias xie=’vim’
source /root/.bashrc
系统级
vim /etc/bashrc
alias xie=’vim’
source /etc/bashrc
取消设置
从文件删除
unalias xie=’vim’
shell中的变量,数值和字符串
字符串
${#string} ##统计字符串的长度
9 #!/bin/bash
10 v1="this is test shell script."
11 echo ${#v1}
执行结果
26
${string:position} 从position开始截取字符串
9 #!/bin/bash
10 v1="this is test shell script."
11 echo ${v1:3}
执行结果:
s is test shell script.
${string:position:length} 从position开始取长度为length的字符串
9 #!/bin/bash
10 v1="this is test shell script."
11 echo ${v1:3:6}
执行结果:
s is t
${string#substring}从开头删除最短匹配字符串
${string##substring}从开头删除最长匹配字符串
${string%substring}从结尾删除最短匹配字符串
${string%%substring}从结尾删除最长匹配字符串
${string#test*.}删除从test开始到.的所有字符(最短匹配)
${string##test*.}删除从test开始到.的所有字符(最长匹配)
9 #!/bin/bash
10 v1="this is test shell script."
11 echo ${v1#this i}
运行结果
s test shell script.