shell 标准输入,标准输出,错误输出
一,标准输入:文件描述符号 0
标准输入来源于键盘、文件,或者其他命令比如管道,通过 read 命令读取
1,键盘输入:
test_cmd.sh 内容
#!/bin/bash echo "enter some word:" read content echo "enter content is:" echo $content
执行 test_cmd.sh ,然后在键盘输入任意内容
./test_cmd.sh enter some word: hello world enter content is: hello world
2,来源文件
# echo 'file_input' > file_input.txt # ./test_cmd.sh < file_input.txt enter some word: enter content is: file_input
3,管道输入
test_cmd_two.sh 内容
#!/bin/bash cat file_input.txt | while read line do echo "Line :$line" done
执行 test_cmd_two.sh
# echo 'file_input' > file_input.txt # echo 'one' >> file_input.txt # echo 'two' >> file_input.txt # cat file_input.txt file_input one two # ./test_cmd_two.sh Line :file_input Line :one Line :two
二,标准输出:文件描述符号 1
标准输出最常用的命令是 echo
test_cmd_three.sh
#!/bin/bash echo "content" > output.txt echo "content" 1> output_two.txt
执行 ./test_cmd_three.sh,然后读取 output.txt output_two.txt 内容,发现效果一样,说明重定向符号 ">" ,默认把标准输出重定向到文件,即 "> $file" 等于 "1> $file"
# ./test_cmd_three.sh # ./test_cmd.sh < output.txt enter some word: enter content is: content # ./test_cmd.sh < output_two.txt enter some word: enter content is: content
三,错误输出:文件描述符号 2
脚本执行时的异常会当做错误输出
test_cmd_four.sh 内容
#!/bin/bash echo "one" echoh "two"
执行文件
# ./test_cmd_four.sh 1> output.txt 2> error.txt # cat output.txt one # cat error.txt ./test_cmd_four.sh: line 4: echoh: command not found #
1 是标准输出 ,2 是错误输出
当然也可以把错误输出重定向到标准输出
# ./test_cmd_four.sh 1> output.txt 2>&1 # cat output.txt one ./test_cmd_four.sh: line 4: echoh: command not found
或者重定向错误输出到空文件
# ./test_cmd_four.sh 1> output.txt 2>/dev/null # cat output.txt one
Leave a Reply