linux命令之交互式输入read


linux命令之交互式输入read
 
read是一个重要的命令,用于从键盘或标准输入中读取输入。
一般只有按回车键的时候才标志输入完毕,但有些情况下没法按回车键,read提供了一种不需要按回车键的方法。
1.-p “提示语句” 变量名
[wang@localhost 桌面]$ vim testcmd.sh
#!/bin/bash
read -p "Enter your name :" name1 name2   //name1前面要空格,可以赋值给多个变量
echo $name1
echo $name2
 
[wang@localhost 桌面]$ chmod +x testcmd.sh 
[wang@localhost 桌面]$ ./testcmd.sh 
Enter your name :william sam
william
sam
[wang@localhost 桌面]$ ./testcmd.sh 
Enter your name :william sam linux    //多余的输入会赋值给最后一个变量
william
sam linux
 
2.-n 输入个数
当输入字符数达到预定数目,则自动退出,不用按回车。
[wang@localhost 桌面]$ read -n 4 -p "Enter your name :" name;echo $name
Enter your name :wangwang    //一个wang是输入的,另一个是echo $name。
 
3.-s 不回显
用于输入密码,对于密码的保护。
[wang@localhost 桌面]$ read -n 4 -s -p "Enter your name :" name;echo $name
Enter your name :wang    //这个是echo $name
 
4.-t 等待输入的秒数
[wang@localhost 桌面]$ read -n 4 -t 2 -p "Enter your name :" name;echo $name
Enter your name :            //等2秒后 自动跳出了
 
或者写个脚本:
[wang@localhost 桌面]$ vim testcmd.sh
#!/bin/bash
if read -t 2 -p "Enter your name :" name
then
        echo $name
else
        echo "Timeout!"
fi
[wang@localhost 桌面]$ ./testcmd.sh 
Enter your name :Timeout!
 
5.-d 自定义定界符
输入自定义的定界符,结束输入。
[wang@localhost 桌面]$ read -d ":" -p "Enter your name :" name;echo $name
Enter your name :name:name
 
6.从标准输入中读取
[wang@localhost 桌面]$ vim testcmd.sh
#!/bin/bash
count=1
cat test.c | while read line    //从test.c读取每一行并赋值给line变量
do
        echo "$count:$line"
        count=$[ count+1 ]
done
 
[wang@localhost 桌面]$ cat test.c
#include <stdio.h>
 
int main()
{
int a = 4;
(++a) += a;
printf("we are the best %d!\n",a);
return 0;
}
 
[wang@localhost 桌面]$ ./testcmd.sh 
1:#include <stdio.h>
2:
3:int main()
4:{
5:int a = 4;
6:(++a) += a;
7:printf("we are the best %d!n",a);
8:return 0;
9:}
注意:上面的cat test.c 也可以换成ls ,ps,grep,find等等命令
 

相关内容

    暂无相关文章