shell script中read的用法

2021-08-11 05:09:04 字數 3308 閱讀 6128

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命令對於輸入字元的判斷

#!/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

FileInputStream中的read 方法

首先這是我自己寫 的時候遇到的乙個問題,我思來想去,終於想通透了,所以想分享給大家,當然這也是乙個非常簡單的問題,大神勿噴。public class io inputstream public static void main string args 但是列印結果就是 246,隔乙個列印乙個,我感到...

Shell Script中FOR迴圈的使用

for迴圈的使用1 for i 0 i 5 i do date date y m d d i days ago showdate showdate date echo showdate done 輸出20120319 20120319 20120318 20120319 20120318 20120...

shell script 中 set的用法

使用set命令可以 設定各種shell選項或者列出shell 變數.單個選項設定常用的特性.在某些選項之後 o引數將特殊特性開啟.在某些選項之後使用 o引數將關閉某些特性,不帶任何引數的set命令將顯示shell的全部變數.除非遇到非法的選項,否則set總是 返回ture.當bash shell被呼...