sh command: exec 2>&1

后端 未结 6 684
名媛妹妹
名媛妹妹 2020-12-24 00:45

What will this command do?

exec 2>&1 
6条回答
  •  -上瘾入骨i
    2020-12-24 01:33

    These day I was suck at this problem too, but now I'm jump out from it. So, please allow me to explain what happen after you input exec 1>&2 in CLI.

    I want to destruct the problem piece by piece, so if you know the knowledge alread just skim it to save your time.

    • What is exec stands for:

    exec is a built-in command in Linux. Different from the tradition command which just fork a sub shell process, exec could change current shell process.

    • What is I/O redirection: Redirection is a feature in Linux. With this you can change the standard input/output devices. In Linux, there are three file descriptors by default. Handle Name Description 0 stdin Standard input 1 stdout Standard output 2 stderr Standard error

    • Let me see an example:

      1. open a new terminal
      2. Get the termianl process process ID $ pstree -p | grep 'term' | tr -d ' '
      3. Check the process file descriptor. $ sudo ls -l /proc/{pid}/fd bash $ pstree -p | grep -i 'terminal' | tr -d ' ' ||||-gnome-terminal-(6008)-+-bash(7641)-+-grep(8355) $ sudo ls -l /proc/7641/fd total 0 lrwx------ 1 alopex alopex 64 Oct 27 19:39 0 -> /dev/pts/3 lrwx------ 1 alopex alopex 64 Oct 27 19:39 1 -> /dev/pts/3 lrwx------ 1 alopex alopex 64 Oct 27 19:39 2 -> /dev/pts/3 lrwx------ 1 alopex alopex 64 Oct 27 19:39 255 -> /dev/pts/3 As you can see, the ls list the PID(6860) process file. First they all name by number(0, 1, 2), second they all link file link to /dev/pts/3, it means whatever standard input/output/error all will show up in pts3.
      4. Change the standard output to /tmp/stdout bash $ ls /tmp/stdout ls: cannot access '/tmp/stdout': No such file or directory $ exec 1>/tmp/stdout $ ls $ pwd $ echo "Are you ok" $ The command output was disappear at that time.
      5. Open a new terminal, to check the proc file bash $ sudo ls -l /proc/7641/fd total 0 lrwx------ 1 alopex alopex 64 Oct 27 19:39 0 -> /dev/pts/3 lrwx------ 1 alopex alopex 64 Oct 27 19:39 1 -> /tmp/stdout lrwx------ 1 alopex alopex 64 Oct 27 19:39 2 -> /dev/pts/3 lrwx------ 1 alopex alopex 64 Oct 27 19:39 255 -> /dev/pts/3 Obviously, we can notice that the 1(file descriptor) already change link to /tmp/stdout. As us except, the standard output transfer to /tmp/stdout
      6. Restore the redirection. bash $ exec 1>&2 $ cat /tmp/stdout a.sh /home/alopex Are you ok $ sudo ls -l /proc/7641/fd total 0 lrwx------ 1 alopex alopex 64 Oct 27 19:39 0 -> /dev/pts/3 lrwx------ 1 alopex alopex 64 Oct 27 19:39 1 -> /dev/pts/3 lrwx------ 1 alopex alopex 64 Oct 27 19:39 2 -> /dev/pts/3 lrwx------ 1 alopex alopex 64 Oct 27 19:39 255 -> /dev/pts/3 Again, the 1(file descriptor) link to the /dev/pts/3, we can see the output again.
    • Summary:

    • exec 1>&2 make the standard output ---> standard error

提交回复
热议问题