shell输入/输出重定向

command > file:将输出重定向到file

command >> file:将输出以追加的方式重定向到file

说明:上述命令的意思是执行command然后将输出的内容存入到file(覆盖还是追加由> 和 >> 决定)

[root@ipha-dev71-1 exercise_shell]# echo 1 > test.sh 
[root@ipha-dev71-1 exercise_shell]# cat test.sh   # 查看文件内容
1
[root@ipha-dev71-1 exercise_shell]# echo 2 >test.sh 
[root@ipha-dev71-1 exercise_shell]# cat test.sh   
2
[root@ipha-dev71-1 exercise_shell]# echo 3 >> test.sh 
[root@ipha-dev71-1 exercise_shell]# cat test.sh 
2
3

command < file:将 file 文件中的内容作为 command 的输入

[root@ipha-dev71-1 exercise_shell]# cat test.sh 
#!/bin/sh
echo "输入1到4之间的数字:"
echo "你输入的数字为:"
read aNum
case $aNum in
    1) echo '你选择了1'
    ;;
    2) echo '你选择了2'
    ;;
    3) echo '你选择了3'
    ;;
    4) echo '你选择了4'
    ;;
    *) echo '你没有输入1到4之间的数字'
    ;;
esac
[root@ipha-dev71-1 exercise_shell]# wc <test.sh 
 16  31 305
[root@ipha-dev71-1 exercise_shell]# wc test.sh
 16  31 305 test.sh

重定向深入讲解:

 0 是标准输入(STDIN),1 是标准输出(STDOUT),2 是标准错误输出(STDERR)。

[root@ipha-dev71-1 exercise_shell]# ls test.sh 
test.sh
[root@ipha-dev71-1 exercise_shell]# ls a.txt
ls: cannot access a.txt: No such file or directory
[root@ipha-dev71-1 exercise_shell]# ls test.sh a.txt 1>file.out 2>file.err   # 1可以省略,2不可以省略;1和>之间不可以有空格,>和file.out间可以有空格
[root@ipha-dev71-1 exercise_shell]# ll
total 36
-rwxrwxrwx 1 root root  70 Aug 27 15:57 del_var.sh
-rwxrwxrwx 1 root root  85 Aug 27 16:13 double_str.sh
-rw-r--r-- 1 root root  51 Aug 28 21:30 file.err
-rw-r--r-- 1 root root   8 Aug 28 21:30 file.out
-rwxrwxrwx 1 root root  58 Aug 27 15:52 read_only.sh
-rwxrwxrwx 1 root root  45 Aug 27 16:05 simple_str.sh
-rwxrwxrwx 1 root root  37 Aug 28 17:59 test1.sh
-rwxrwxrwx 1 root root   0 Aug 28 17:56 test2.sh
-rwxrwxrwx 1 root root 305 Aug 28 17:49 test.sh
-rwxrwxrwx 1 root root  69 Aug 27 15:47 variable.sh
[root@ipha-dev71-1 exercise_shell]# cat file.out 
test.sh
[root@ipha-dev71-1 exercise_shell]# cat file.err 
ls: cannot access a.txt: No such file or directory
[root@ipha-dev71-1 exercise_shell]# ls test.sh a.txt 1>file.out 2>&1   # 将 stdout 和 stderr 合并后重定向到 file.out
[root@ipha-dev71-1 exercise_shell]# cat file.out 
ls: cannot access a.txt: No such file or directory
test.sh

/dev/null 是一个特殊的文件,写入到它的内容都会被丢弃;如果尝试从该文件读取内容,那么什么也读不到。但是 /dev/null 文件非常有用,将命令的输出重定向到它,会起到"禁止输出"的效果。

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

[root@ipha-dev71-1 exercise_shell]# ls test.sh a.txt >/dev/null 2>&1
原文地址:https://www.cnblogs.com/wang-mengmeng/p/11425316.html