linux-7 重定向、管道、环境变量

1、标准输入、标准输出、标准错误

  stdin、stdout、stderr

  用户通过终端与shell交互

  shell缺省打开3个文件句柄

  子进程继承父进程打开的文件

  进程从stdin 读取用户输入

  从stdout 、stderr 输出信息

  指向同一个设备文件——终端

  a、重定向——标准输出

    有的时候,不想输出到终端上(命令结果需要处理)

    使用shell 的功能:重定向

    ps -ef > out -----ps -ef 返回的内容写入 out文本中

    ps -ef 1> out  同上

    0-stdin、1-stdout、2-stderr

    /dev/null ---重定向到这里相当于扔到垃圾场,无法找到输出内容

    > 有内容时会覆盖掉, >>追加内容

  b、重定向——标准错误

    ps -ef 2 > err.log

   同时重定向stdout 和stderr 到同一个文件

    command > both 2 > &1 -----command 重定向到both文件,同时将标准错误重定向到标准输出

    注意次序,从左到右:反过来则不可以  

   同时重定向 stdout、stderr 到不同的文件

    command > out 2 > err

  c、重定向——标准输入

    有时候需要从文件里面读取内容,而不是终端设备

    1.py < readdate.dat

2、管道

  经常需要将一个命令的输出内容,给另一个命令作为输入的内容进行处理

  ps -ef 和 grep python  

  可以:

  ps -ef | tmp.out

  grep python tmp.out

  使用管道可以更方便

  ps -ef | grep python

  将前面的ps -ef 命令的stdout(本来输出到终端设备的)重定向到一个临时管道设备里

  同时将后一个命令 grep python 的stdin 重定向到这个临时的管道设备

  管道的一些用法

  让stdout 和stderr 同时重定向到管道

  python both.py 2 > &1 | grep err

  连续使用管道

  ps -ef | grep python | grep -v grep.....

3、环境变量

  什么是shell 变量

    a=1;b=2 有名字的对象

  什么是shell 环境变量

    特殊意义的变量,用来影响进程的行为,可以传递给子进程

  printenv

  环境变量是如何生成的?

    操作系统为每个进程保存

    每个进程可能会修改环境变量,通过初始化脚本或者用户操作

    子进程继承父进程的环境变量

  重新登录可生效改变的环境变量

  对BASH来说

    login shell

      /etc/profile, ~/.bash_profile,~/.bash_login,~/.profile

    non-login shell

      ~/.bashrc

  手动执行初始化脚本: source .bashrc

原文地址:https://www.cnblogs.com/feihan/p/14146382.html