9.4 输入、输出与重定向

本节介绍常用的输出命令(echoprintf)以及标准输入/输出的重定向。

echo 命令

echo 用于向标准输出打印字符串,其用法类似于 PHP。

echo string

常见用法

  1. 显示普通字符串:

    echo "It is a test"
    
  2. 显示转义字符:

    echo "\"It is a test\""
    
  3. 显示变量:

    read name 
    echo "$name It is a test"
    
  4. 显示换行:

    echo -e "OK! \n" # -e 开启转义
    
  5. 不换行输出:

    echo -e "OK! \c" # -e 开启转义 \c 不换行
    
  6. 输出到文件:

    echo "It is a test" > myfile
    
  7. 原样输出字符串(单引号):

    echo '$name\"'
    
  8. 输出命令执行结果:

    echo `date`
    

printf 命令

printf 模仿 C 语言的 printf,遵循 POSIX 标准,便于移植。

printf format-string [arguments...]
  • format-string 为格式控制字符串
  • arguments 为参数列表

示例:

printf "%s\n" "Hello, Shell"

更复杂的例子:

printf "%-10s %-8s %-4s\n" 姓名 性别 体重kg
printf "%-10s %-8s %-4.2f\n" 郭靖 男 66.1234

printf 支持多种格式标志和转义序列。

标准输入/输出重定向

Unix 命令通常从标准输入读取,从标准输出打印。可以通过符号改变这些默认行为。

操作 说明
command > file stdout 重定向到 file(覆盖)
command >> file stdout 追加到 file
command < file stdin 从 file 读取
n > file 将文件描述符为 n 的输出重定向到 file
n >> file 将文件描述符为 n 的输出追加到 file
n >& m 将输出文件 m 和 n 合并
n <& m 将输入文件 m 和 n 合并
<< tag Here document,用 tag 开始和结束的内容作为输入

文件描述符 0 为 stdin, 1 为 stdout, 2 为 stderr。

输出重定向示例

who > users
cat users

追加示例:

echo "foo" >> users

输入重定向示例

wc -l < users

混合重定向

command1 < infile > outfile

stderr 重定向

command 2> file          # stderr
command > file 2>&1      # stdout 和 stderr 都重定向
command > /dev/null 2>&1 # 丢弃所有输出

Here document

cat << EOF
第一行
第二行
EOF

/dev/null

/dev/null 是个“黑洞”,写入的数据会被丢弃,常用于抑制输出。

command > /dev/null 2>&1

results matching ""

    No results matching ""