SHELL脚本学习(五)用户输入

获取用户输入
1、基本的读取

read命令从标准或其他文件描述符读取数据,获取输入后,read命令将值存入变量中。
命令格式:

read variable
选项-p:提示信息

#!/usr/bin/bash
read -p "Enter your name:" name
echo hello $name
~$ ./test.sh
Enter your name:lintao
hello lintao
2、超时
使用read命令时要小心,脚本可能一直停在read命令处。如果不管是否有数据输入脚本都要继续执行,则 
可以使用-t选项,后面跟要等待的秒数
#!/usr/bin/bash
if read -t 5 -p "Enter your name:" name
then
    echo hello $name
else
    echo null 
fi
~$ ./test.sh
Enter your name:null
~$ ./test.sh
Enter your name:lintao
hello lintao
3、无显示读取
有时想要从脚本用户处得到输入,又不想显示在屏幕上。这时可以使用 -s选项
#!/usr/bin/bash
if read -s -p "Enter your password:" passwd
then
    echo " ";
    echo passeord=$passwd;
else
    echo null 
fi
~$ ./test.sh
Enter your password: 
passeord=123456
4、从文件中读取

下面两种方式实现输出文件自身的内容。

1、通过cat命令和管道读取
#!/usr/bin/bash
cat ./test.sh| while read line
do
    echo $line
done 
2、通过输入重定向读取
#!/usr/bin/bash
while read line
do
    echo $line
done < ./test.sh
实战演练

检查文件中的 IP列表 是否能连通

#!/usr/bin/bash

echo scrip name is $(basename $0)

# 输入文件名
 while read -p "input file path: " filename
 do
  # 文件名为空 或者 是 quit 则退出
     if [ -z $filename ] || [ $filename = quit ]
     then
          echo exit
          break
     fi

     if [ -e $filename ]
     then
          cat $filename | while read ip
          do
               echo ip : $ip 
               ping -c 3 $ip
          done
     else
          echo file $filename not exists
     fi
 done
 echo end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值