美文网首页
Linux 输入重定向和输出重定向

Linux 输入重定向和输出重定向

作者: 月饮沙 | 来源:发表于2020-11-20 11:39 被阅读0次

    输入重定向

    使用输入重定向 <,<<

    • < 将需要交互输入的内容存放到文件中,用来当做命令的输入。
      注意后面必须是文件,不能直接写字符串。可以用来解决脚本中交互命令的输入问题。
    • << 一般和cat联合使用,用于多行内容写入/追加到文件中

    示例

    # 创建一个空文件
    [root@localhost ~]# touch hosts
    [root@localhost ~]# cat hosts
    # << 将两个EOF之间的内容作为输入,重定向到file中。
    # EOF可以更改为任意符号,只要开头和结尾一致即可
    [root@localhost ~]# cat > file <<EOF
    > y
    > 
    > 
    > EOF
    [root@localhost ~]# cat file 
    y
    
    
    # < 将file中的y作为输入
    [root@localhost ~]# cp /etc/hosts hosts <file 
    cp: overwrite ‘hosts’? 
    [root@localhost ~]# cat hosts 
    127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
    ::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
    
    

    输出重定向

    输出重定向 >,>>,1>,2>,&>,1>>,2>>,&>>

    • >将输出重定向到文件中,会替换掉现有文件内容
    • >>将输出重定向到文件中,会追加在现有文件的结尾
    • 1将正确信息输出
    • 2将错误信息输出
    • &将正确信息和错误信息一起输出

    示例

    # 创建一个新文件
    [root@localhost ~]# touch test
    [root@localhost ~]# cat test
    # 初始文件为空,添加一行内容
    [root@localhost ~]# echo 12345 > test
    [root@localhost ~]# cat test
    12345
    # > 覆盖文件
    [root@localhost ~]# echo 23445 >test
    [root@localhost ~]# cat test
    23445
    # >>在文件末尾追加
    [root@localhost ~]# echo 1234 >>test
    [root@localhost ~]# cat test
    23445
    1234
    
    # 消息重定向
    echo "ls && cp host test" > test.sh
    # 默认错误消息会输出到屏幕上,正确的消息重定向到文件中
    [root@localhost ~]# sh test.sh > test
    cp: cannot stat ‘host’: No such file or directory
    [root@localhost ~]# cat test
    anaconda-ks.cfg
    file
    hosts
    original-ks.cfg
    test
    test.sh
    # 1 将正确的消息重定向到文件中
    [root@localhost ~]# sh test.sh 1> test
    cp: cannot stat ‘host’: No such file or directory
    [root@localhost ~]# cat test
    anaconda-ks.cfg
    file
    hosts
    original-ks.cfg
    test
    test.sh
    # 2 将错误的消息重定向到文件中
    [root@localhost ~]# sh test.sh 2> test
    anaconda-ks.cfg  file  hosts  original-ks.cfg  test  test.sh
    [root@localhost ~]# cat test
    cp: cannot stat ‘host’: No such file or directory
    # & 将正确的和错误的消息都重定向到文件中
    [root@localhost ~]# sh test.sh &> test
    [root@localhost ~]# cat test
    anaconda-ks.cfg
    file
    hosts
    original-ks.cfg
    test
    test.sh
    cp: cannot stat ‘host’: No such file or directory
    

    相关文章

      网友评论

          本文标题:Linux 输入重定向和输出重定向

          本文链接:https://www.haomeiwen.com/subject/braovktx.html