目录
一、变量的定义
- 定义本身:变量存在的意义
- 命令无法操作一直变化的目标,用一串固定的字符来表示不固定的目标可以解决此问题
二、shell脚本中变量的定义方法
1.环境级别
export a=1
在环境关闭后变量失效
2.用户级别
vim ~/.bash_profile
###
export a=1
###
3.系统级别
vim /etc/profile
vim /etc/profile.d/test.sh
env #查看变量
rm -fr /etc/profile.d/test.sh
vim ~/.bash_profile #删除变量行
unset a #清除变量
shell也是个变量:
4.变量名称可包含的字符/定义规则
- 字母;下划线_;数字
- 不能用数字开头
建议:
变量名称短全用大写字符
变量名称长用_区分子类
WESTOS
Westos_Linux
westoS_Linux
三、变量的转译
1.转译
~ | ~ |
---|---|
\ | 转译单个字符 |
“” | 弱引用,批量转译个数字符 不能转译"\ " “” “$” “!” |
‘’ | 强引用 |
$$ | 代表当前进程id |
2.声明
a=1
echo $ab
echo ${a}b
3.变量的数组
a=(1 2 3 4 5 6) #数组
echo ${a[0]} #数组中第一个元素
echo ${a[1]} #数组中第二个元素
echo ${a[-1]} #数组中最后一个元素
echo ${a[@]} #数组中所有元素
echo ${a[*]} #数组中所有元素
echo ${#a[@]} #数组中元素的个数
echo ${a[@]:0:3} #第一个元素后三个元素
echo ${a[@]:3:3} #第三个元素后三个元素
unset a[0] #删除数组中的第1个元素
a[0]=1 #添加一个元素
unset a #删除a这个数组
四、Linux中命令的别名设定
alias xie='vim' #临时设定
vim ~/.bashrc #只针对当前用户生效
vim /etc/bashrc #针对系统所有用户生效
vim /etc/skel/.bashhrc #针对新建的用户生效
alias #查看
unalias xie #删除
五、用户环境变量的更改
系统中存在脚本,但没有办法像/usr/ls那样在任何情况下都使用,需要设定$PATH!
vim ~/.bash_profile
export PATH=$PATH:/mnt
vim /etc/bash_profile
1.直接利用命令执行结果
- $()|优先执行
- TEST=hostname|TEST=$(hostname)
2.脚本中的传参
在脚本外需要写内容的时候,我们脚本无法读取,所以要在脚本内写入一个符号用来传参
(1)非交互模式传参
vim /mnt/test.sh
###
echo '$0' is $0
echo '$1' is $1
echo '$2' is $2
echo '$3' is $3
echo '$*' is $*
echo '$@' is $@
echo '$#' is $#
###
sh /mnt/test.sh 1 2 3
运行结果中:
$0 is /mnt/test.sh #脚本本身
$1 is 1 #脚本后所输入的第一串字符
$2 is 2 #脚本后所输入的第二串字符
$3 is 3 #脚本后所输入的第三串字符
$* is 1 2 3 #脚本后所输入的所有字符"1 2 3"
$@ is 1 2 3 #脚本后所输入的所有字符"1""2""3"
$# is 3 #脚本后所输入的字符串个数
(2)交互模式传参
vim test.sh
###
read -p "Please input word:" -s WORD
echo ""
echo $WORD
###
#read word 对word赋值
#-p输出提示语
#-s隐藏输入内容
#echo "" 换行
六、脚本函数
READ(){
read -p "Please input word:" -s WORD
echo ""
echo $WORD
[ "$WORD" = "exit" ]&&{
echo bye!
exit
}||{
READ
}
}
READ
练习脚本
sh create_user.sh
Please input username: westos
westos exist> westos is exist>Please input username:
westos not existplease input password: 无回显密码
此用户会自动建立并且密码为提示后设定的密码
并显示:westos is created
并再次提示Please input username:
当Please input username:exit
此脚本退出
READ()
{
read -p "Please input username:" -s USER
echo ""
[ "$USER" = "exit" ]&&{
echo -e "$USER is exit"
}||{
useradd $USER &>/dev/null&&{
read -p "Please input password:" -s PASSWORD
echo $PASSWORD | passwd -stdin $USER &>/dev/null
echo ""
echo -e "$USER is created!"
READ
}||{
echo -e "$USER is exit!"
READ
}
}
}
READ