linux/unix 命令运行逻辑

一般unix/linux系统命令运行会打开三个文件:

  1. 标准输入文件(stdin):stdin的文件描述符为0,Unix程序默认从stdin读取数据
  2. 标准输出文件(stdout):stdout的文件描述符为1, Unix程序默认向stdout输出数据
  3. 标准错误文件(stderr):stderr的文件描述符为2,Unix程序会向stderr流中写入错误信息

    shell 重定向输入

    ```bash

    将输入 重定向至test.txt

    wc -l < test.txt

输出结果:2

  1. <a name="EhrdF"></a>
  2. #### shell 重定向输出
  3. ```bash
  4. # 将结果输出重定向 到test.txt
  5. ls > test.txt
  6. # 将结果叠加输出重定向 到test.txt
  7. pwd >> test.txt
  8. cat test.txt
  9. # basic_common.sh
  10. # io_redirection.sh
  11. # process_control.sh
  12. # shell_operators_practise.sh
  13. # shell_test.sh
  14. # test
  15. # test.txt

不同类型的重定向输出

  1. # stderr 重定向到file
  2. pwd 2>file
  3. pwd 2>>file
  4. # 标准输出和标准错误文件都重定向到file
  5. pwd > file 2>&1
  6. pwd >> file 2>&1
  7. # 标准输入重定向到file1 、标准输出重定向到file2
  8. pwd < file1 > file2

特殊的重定向方式

  1. wc -l << EOF
  2. test
  3. www.baidu.com
  4. EOF
  5. cat << EOF
  6. www.baidu.com
  7. EOF

文件引用

  1. # test1.sh文件
  2. url="www.baidu.com"
  3. # test2.sh文件
  4. . ./test1.sh
  5. # 或者
  6. source ./test1.sh
  7. chmod +x test2.sh
  8. # 结果输出:www.baidu.com