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
5、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
执行:
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