1、read 命令键盘读取变量的值
从键盘读取变量的值,通常用在 shell 脚本中与用户进行交互的场合。该命令可以一次读取多个变量的值,变量和输入的值都需要使用空格隔开。
[root@test ~]# read test
1
[root@test ~]# echo $test
1
(1)read常用语法及参数
A、从标准输入读取一行并赋值给变量
[root@test ~]# read test
1
B、从标准输入读取多个值,遇到第一个空白符或换行符。把用户键入的第一个词存到变量a,把该行的剩余部分保存到变量b。
[root@test ~]# read a b
1 2 3
[root@test ~]# echo $a $b
1 2 3
[root@test ~]# echo $a
1
[root@test ~]# echo $b
2 3
[root@test ~]#
C、read -s隐藏输入信息
[root@test ~]# read -s a
[root@test ~]# echo $a
1111
[root@test ~]#
D、输入时间限制
超过2秒没有输入就退出。
[root@test ~]# read -t 2 a
[root@test ~]# echo $a
[root@test ~]# read -t 2 a
1
[root@test ~]# echo $a
1
[root@test ~]#
E、输入长度限制
最多只允许输入2个字符
[root@test ~]# read -n 2 a
11[root@test ~]#
F、使用-r参数输,允许让输入中的内容包括:\识别为普通字符
[root@test ~]# read -r a
lll\ hshhs
[root@test ~]# echo $a
lll\ hshhs
[root@test ~]#
G、-p 用于给出提示符
[root@test ~]# read -p "please input: " password
please input: 123456
[root@test ~]# echo $password
123456
[root@test ~]#
2、if语句流程
(1)单if语法格式
if 条件
then
commands
fi
Eg:查看ls命令是否执行成功
[root@test ~]# more if.sh
#!/bin/bash
if ls /home
then
echo "it is ok"
fi
[root@test ~]# sh if.sh
demo.py pycharm-community-2020.2.3.tar.gz
it is ok
[root@test ~]#
(2)if…else
语法格式:
if 条件;then
commands
else
commands
fi
Eg:查看指定目录是否存在
[root@test ~]# vi test.sh
#!/bin/bash
read -p "输入目录名称" a
if ls $a >>/dev/null
then
echo "$a 存在"
else
echo "$a 不存在"
fi
[root@test ~]# sh test.sh
输入目录名称home
ls: 无法访问home: 没有那个文件或目录
home 不存在
[root@test ~]# sh test.sh
输入目录名称/home
/home 存在
[root@test ~]#
注:bash -v [脚本] 可检查脚本语法错误;
bash -x [脚本] 可显示脚本执行过程。
(3)多条件if语句
语法结构:
if 条件1 ; then
commands
elif 条件2 ; then
commands
elif 条件3 ; then
commands
.......
else
commands
fi
Eg:查看指定用户是否存在
[root@test ~]# vi test1.sh
#!/bin/bash
read -p "请输入用户名:" user
if grep $user /etc/passwd
then
echo "当前系统中存在此用户"
elif ls -d /home/$user
then
echo "$user 用户不存在"
echo "$user 有主目录"
else
echo "系统用户不存在"
echo "系统不存在用户目录"
fi
[root@test ~]# sh test1.sh
请输入用户名:test
ls: 无法访问/home/test: 没有那个文件或目录
系统用户不存在
系统不存在用户目录
[root@test ~]#
个人公众号,微信搜索:linux言叙