shell 输入和输出

1. 读取键盘输入

read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]

  • -p 提示语句,后面接输入提示信息
  • -n 字符个数,限制输入长度
  • -s 屏蔽回显,屏幕上不显示输入内容,一般用于密码输入
  • -t 超时时间,等待输入超时时间
  • -d 输入界限,遇到该符号,终止输入
  • -r 屏蔽特殊字符 \ 的转义功能
$ read -s -t 5 -n 6 -p "Enter password: " password
$ echo $password

2. echo 转义输出

$ echo "hello\n world."
hello\n world.
$ echo -e "hello\n world."
hello
 world.

3. 重定向

一般情况下,每个 Unix/Linux 命令运行时都会打开三个文件:

  • 标准输入文件(stdin):stdin 的文件描述符为0,Unix 程序默认从 stdin 读取数据。
  • 标准输出文件(stdout):stdout 的文件描述符为1,Unix 程序默认向 stdout 输出数据。
  • 标准错误文件(stderr):stderr 的文件描述符为2,Unix 程序会向 stderr 流中写入错误信息。
$ command < infile > outfile

同时替换输入和输出,command < infile 将 stdin 重定向到 infile,然后 command > outfile 将 stdout 重定向到 outfile 中。

(1)如果希望将 stdout 和 stderr 合并后重定向到 file,可以这样写:

$ command > file 2>&1

(2)如果希望执行某个命令,但又不希望在屏幕上显示输出结果,那么可以将输出重定向到 /dev/null:

$ command > /dev/null

/dev/null 是一个特殊的文件,写入到它的内容都会被丢弃;如果尝试从该文件读取内容,那么什么也读不到。

(3)如果希望屏蔽 stdout 和 stderr,可以这样写:

$ command > /dev/null 2>&1

猜你喜欢

转载自www.cnblogs.com/yutb/p/11236839.html