16.Linux Bash Shell通过`read`命令读取用户输入


欢迎访问个人网络日志🌹🌹知行空间🌹🌹


Linux Shell获取用户输入

处理简单输入

shell与用户交互式输入使用的是read命令,一个简单的例子:

#!/bin/bash

echo "Please Input Your Name: "
read name
echo "The Input Name Is $name"

执行,

bash test.sh
# Please Input Your Name: 
# Lee
# The Input Name Is Lee

read命令本身支持多种选项,使用-p选项可以将输入提示符"Please Input Your Name: "放到read命令那一行:

#!/bin/bash
echo 
read -p "Please Input Your Name: " name
echo "The Input Name Is $name"

这样输入和提示符就都放在同一行了,
执行,

bash test.sh
# Please Input Your Name: Job Lee
# The Input Name Is Job Lee

不过从上面的输入可以看到,Job Lee被解析成了一个值,虽然中间有空格。这是因为read命令后面只有一个变量接收参数,如果期望接收多个参数,就在read命令后面多放几个变量即可如果输入的参数比接收的变量多,那么多余的参数都会被放在最后一个变量中。

#!/bin/bash

read -p "Input Values:" value1 value2 value3
echo "The Value1 is $value1"
echo "The Value2 is $value2"
echo "The value3 is $value3"

执行,

bash test.sh
# Input Values:value1 value2 value3 value4 value5
# The Value1 is value1
# The Value2 is value2
# The value3 is value3 value4 value5

read命令后面也可以不跟参数,此时用户输入的值就都放在环境变量REPLY中。

#!/bin/bash

read -p "Input Values:"
echo "The Values are $REPLY"

执行,

bash test.sh

# Input Values:v1 v2 v3
# The Values are v1 v2 v3

控制等待

**read命令支持-t参数,控制等待输入时间,单位是秒数,如果超时,read 命令会返回一个非零退出状态码。**这通常可以用于ifwhile的条件。

#!/bin/bash

if read -t 3 -p "Input Value: " value; then
    echo "The Input Value Is $value"
else
    echo "Timeout."
fi

执行,

bash test.sh
# Input Value: 1 
# The Input Value Is 1
bash test.sh
# Input Value: Timeout.

也可以不对输入过程计时,而是让 read 命令来统计输入的字符数。当输入的字符达到预设
的字符数时,就自动退出,将输入的数据赋给变量。

#!/bin/bash
#
read -n1 -p "Do you want to continue [Y/N]? " answer
case $answer in
    Y | y) echo
        echo "fine, continue on…";;
    N | n) echo
        echo OK, goodbye
    exit;;
esac
echo "This is the end of the script"

执行,

bash test.sh
# Do you want to continue [Y/N]? Y
# fine, continue on…
# This is the end of the script

本例中将 -n 选项和值 1 一起使用,告诉 read 命令在接受单个字符后退出。只要按下单个字符回答后,read 命令就会接受输入并将它传给变量,无需按回车键。

通过read --help命令可以查看到read支持的选项参数-n nchars读取 nchars 个字符之后返回,而不是等到读取换行符。

隐藏输入

上面介绍的输入值都会实时显示在屏幕上,在输入密码等隐私数据时,通常希望输入内容能够隐藏。

-s选项可以避免在 read 命令中输入的数据出现在显示器上(实际上,数据会被显示,只是
read 命令会将文本颜色设成跟背景色一样)。

#!/bin/bash
read -s -p "Enter your password: " pass
echo
echo "Is your password really $pass? "

执行,

bash test.sh

# Enter your password: 
# Is your password really yhih? 

从文件中读取

也可以用 read命令来读取Linux系统上文件里保存的数据。

每次调用 read 命令,它都
会从文件中读取一行文本。当文件中再没有内容时, read 命令会退出并返回非零退出状态码。

最难的部分是将文件中的数据传给 read 命令。最常见的方法是对文件使用 cat 命令,将
结果通过管道直接传给含有 read 命令的 while 命令。

#!/bin/bash
count=1
cat test | while read line
do
    echo "Line $count: $line"
    count=$[ $count + 1]
done
echo "Finished processing the file"

执行,

cat test
# this is line1
# this is line2

bash test.sh
# Line 1: this is line1
# Line 2: this is line2
# Line 3: 
# Finished processing the file

while 循环会持续通过 read 命令处理文件中的行,直到 read 命令以非零退出状态码退出。


欢迎访问个人网络日志🌹🌹知行空间🌹🌹


本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码

)">
< <上一篇
下一篇>>