输入输出
标准输入输出
文件描述符 0 通常是标准输入(STDIN),1 是标准输出(STDOUT),2 是标准错误输出(STDERR)。
- echo
用于字符串的输出
(1)显示普通字符串
echo "It is a test"
或者没双引号也一样:
echo It is a test
(2)显示转义字符
echo "\"It is a test\""
"It is a test"
(3)显示变量
read 命令从标准输入中读取一行,并把输入行的每个字段的值指定给 shell 变量
#!/bin/sh
read name1 name2
echo "$name1 $name1 It is a test"
以上代码保存为 test.sh,name 接收标准输入的变量,结果将是:
[root@www ~]# sh test.sh
Hello World #标准输入
Hello World It is a test #输出
(4)显示换行
echo -e "OK! \n" # -e 开启转义
echo "It is a test"
OK!
It is a test
(5)显示不换行
#!/bin/sh
echo -e "OK! \c" # -e 开启转义 \c 不换行
echo "It is a test"
OK! It is a test
(6)显示结果定向至文件
echo "It is a test" > myfile
(7)原样输出字符串,不进行转义或取变量(用单引号)
echo '$name\"'
$name\"
(8)显示命令执行结果
echo `date` #注意: 这里使用的是反引号 `, 而不是单引号 '。
Thu Jul 24 10:08:46 CST 2014
- printf
printf 命令模仿 C 程序库(library)里的 printf() 程序。printf 由 POSIX 标准所定义,因此使用 printf 的脚本比使用 echo 移植性好。
printf format-string [arguments…]
format-string: 为格式控制字符串
arguments: 为参数列表。
#!/bin/bash
#author:菜鸟教程
printf "%-10s %-8s %-4s\n" 姓名 性别 体重kg
printf "%-10s %-8s %-4.2f\n" 郭靖 男 66.1234
printf "%-10s %-8s %-4.2f\n" 杨过 男 48.6543
printf "%-10s %-8s %-4.2f\n" 郭芙 女 47.9876
输入输出重定向
重定向意思是不再是标准的输入输出,而是要将输入输出重定向到文件或者其他地方。
命令 | 说明 |
---|---|
command > file | 将输出重定向到 file。 |
command < file | 将输入重定向到 file。 |
command >> file | 将输出以追加的方式重定向到 file。 |
n > file | 将文件描述符为 n 的文件重定向到 file。 |
n >> file | 将文件描述符为 n 的文件以追加的方式重定向到 file。 |
n >& m | 将输出文件 m 和 n 合并。 |
n <& m | 将输入文件 m 和 n 合并。 |
<< tag | 将开始标记 tag 和结束标记 tag 之间的内容作为输入。 |