shell script中read的用法

1、read基本读取

#!/bin/bash
#testing the read command

echo -n "Enter you name:"   #echo -n 让用户直接在后面输入 
read name  #输入的多个文本将保存在一个变量中
echo "Hello $name, welcome to my progra

执行:

# ./read.sh
Enter you name: yuan
Hello yuan, welcome to my program

2、read -p (直接在read命令行指定提示符)

#!/bin/bash
#testing the read -p option
read -p "Please enter your age: " age
days=$[ $age * 365 ]
echo "That makes you over $days days old!"

3、read -p(指定多个变量)

#!/bin/bash
# entering multiple variables

read -p "Enter your name:" first last
echo "Checking data for $last, $first"
执行:

# ./read1.sh
Enter your name: a b
Checking data for b, a
4、超时、等待输入的秒数(read -t)

#!/bin/bash
# timing the data entry

if read -t 5 -p "Please enter your name: " name     #记得加-p参数, 直接在read命令行指定提示符
then
    echo "Hello $name, welcome to my script"
else
    echo 
    echo "Sorry, too slow!"
fi
执行:

# ./read3.sh
Please enter your name: 
Sorry, too slow!


# ./read3.sh 
Please enter your name: wang
Hello wang, welcome to my script
4、read命令对于输入字符的判断

  • []有比较的判断的功能
  • -o代表or
  • &&在shell中的用法是如果&&左边的命令执行成功(即$?=0)时才能执行&&右边的命令

#!/bin/bash


read -p "Please input(Y/N):" yn
[ "$yn" == "Y" -o "$yn" == "y" ]&&echo  "OK,continue"&&exit 0
[ "$yn" == "N" -o "$yn" == "n" ]&&echo "Oh,interrupt!"&&exit 0
echo "i don't konw what your choice is"&&exit 0
5、执行

yuanqiangfei@ubuntu:~/script$ ./sh01.sh 
Please input(Y/N):y
OK,continue
yuanqiangfei@ubuntu:~/script$ ./sh01.sh 
Please input(Y/N):n
Oh,interrupt!
6、隐藏方式读取(read -s)

  • 在中括号 [] 内的每个组件都需要有空白键来分隔;
  • 在中括号内的变量,最好都以双引号括号起来;
  • 在中括号内的常数,最好都以单或双引号括号起来。
  • ==和!=两边都要有空格
  • []有比较的判断的功能

#!/bin/bash
#entering muiltple variables

while true
do
        read -s -p "Please enter your password:"  passwd

        [ "$passwd" == "123456" ]&&echo "password is right!"&&exit 0
        [ "$passwd" != "123456" ]&&echo "password is not right,Please input again!"&&continue
done
执行:

yuanqiangfei@ubuntu:~/script$ ./read.sh 
Please enter your password:password is right!
yuanqiangfei@ubuntu:~/script$ ./read.sh 
Please enter your password:password is not right,Please input again!
Please enter your password:

7、从文本中读取

#!/bin/bash
# reading data from a file

count=1
cat test | while read line
do
   echo "Line $count: $line"
   count=$[ $count + 1 ]
done
echo "Finished processing the file"
执行结果:

 ./read6.sh
Line 1: The quick brown dog jumps over the lazy fox.
Line 2: This is a test, this is only a test.
Line 3: O Romeo, Romeo! Wherefore art thou Romeo?
Finished processing the file
































 
 
 
 
 
 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值