read
$ISF
read
read [options] [variable...]
options:
-
-p
prompt 提示语句 -
-t
timeout 超时 -
-s
slient 不显示用户输入(用于输入密码) -
-i
用于提供默认值,必须和-e
一起使用
# 提供默认值 $USER
# 读取输入,保存到变量名 name
[admin@localhost ~]$ read -e -p "Your name: " -i $USER name && echo $name
Your name: admin
admin
$ cat test-integer.sh
#!/bin/bash
read -p "Enter an integer: " num
# 判断是否整数
if [[ "$num" =~ -?[[:digit:]]+ ]]; then
# 判断正负
if (( num > 0 )); then
printf "%s is positive\n" $num
elif (( num < 0 )); then
printf "%s is negative\n" $num
else
printf "%s is zero\n" $num
fi
# 判断奇偶
if (( num % 2 == 0 )); then
printf "%s is even\n" $num
else
printf "%s is odd\n" $num
fi
# 不是整数,重定向到 stderr
else
echo "$num is not an integer" >&2
exit 1
fi
IFS
环境变量 IFS
(internal field separator): 默认值是空白字符;
作用:作为 read
的分隔符
$ ./user_info.sh
Enter a username: admin
username: admin
group: admin
uid: 1000
gid: 1000
home: /home/admin:/bin/bash
$ cat ./user_info.sh
#!/bin/bash
# root:x:0:0:root:/root:/bin/bash
read -p "Enter a username: " -ei $USER user
user_info=$(grep "^$user" /etc/passwd)
if [ -n "$user_info" ]; then
# 临时改变分隔符为 :
# 用 <<< 将变量 user_info 的值作为标准输入传给 read
IFS=":" read username passwd uid gid group home <<< "$user_info"
printf "\nusername: %s" $username
printf "\ngroup: %s" $group
printf "\nuid: %s" $uid
printf "\ngid: %s" $gid
printf "\nhome: %s" $home
printf "\n\n"
else
echo "No such user: $user">&2
exit 1
fi
操作符 >>>
>>>
用于重定向字符串
command1 | command2
:管道将 command1
的输出作为 command2
的输输入,但是管道会创建一个 subshell (复制 command1
的环境变量) 来执行 comand2
,command2
执行完毕后销毁 subshell (清除环境变量)
# $variable 的值为空
$ echo "Hello" | read variable; echo $variable
# $variable 的值为 "Hello"
$ read variable <<< "Hello"; echo $variable
Hello