Images in this article are not well-scaled.

Disclaimer: This passage contains notes and insights gathered from the internet. The content is used for educational purposes and attributed to the original authors. I do not claim any ownership over the material.

Redirection & Piping

Screenshot 2023-01-10 at 12.00.52.png

  • STDIN (0) - Standard input (data fed into the program)
  • STDOUT (1) - Standard output (data printed by the program, defaults to the terminal)
  • STDERR (2) - Standard error (for error messages, also defaults to the terminal)

Redirection

  • > create new file to save output, or clear all contents and save output.
  • >> append contents into the file.
$ cat myoutput
barry.txt
bob
example.png
firstfile
foo1
myoutput
video.mpeg

$ wc -l barry.txt > myoutput
$ cat myoutput
7 barry.txt
$ cat myoutput
7 barry.txt
$ ls >> myoutput
$ cat myoutput
7 barry.txt
barry.txt
bob
example.png
firstfile
foo1
myoutput
video.mpeg
  • < read data from the file
$ wc -l myoutput
8 myoutput
$ wc -l < myoutput
8
$ wc -l < barry.txt > myoutput
$ cat myoutput
7

  • 2> redirect error message
  • >& or &> or 2>&1 redirect error message and normal output
$ ls -l video.mpg blah.foo > myoutput 2>&1
// $ ls -l video.mpg blah.foo >& myoutput

$ cat myoutput
ls: cannot access blah.foo: No such file or directory
-rwxr--r-- 1 ryan users 6 May 16 09:14 video.mpg

Piping

What this operator does is feed the output from the program on the left as input to the program on the right.

$ ls -l /etc | less
(Full screen of output you may scroll. Try it yourself to see.)

$ ls -l ~ | grep '^.....w'
drwxrwxr-x 3 ryan users 4096 Jan 21 04:12 dropbox

$ ls -l /projects/ghosttrail | tail -n +2 | sed 's/\s\s*/ /g' | cut -d ' ' -f 3 | sort | uniq -c
8 anne
34 harry
37 tina
18 ryan

$ ls -l /etc | tail -n +2 | sort
drwxrwxr-x 3 nagios nagcmd 4096 Mar 29 08:52 nagios
drwxr-x--- 2 news news 4096 Jan 27 02:22 news
drwxr-x--- 2 root mysql 4096 Mar 6 22:39 mysql
...

Summary

Screenshot 2023-01-10 at 11.58.12.png

#  redirect a.out's stdin to read from file infile.txt:
$ ./a.out < infile.txt

# redirect a.out's stdout to print to file outfile.txt:
$ ./a.out > outfile.txt

# redirect a.out's stdout and stderr to a file out.txt
$ ./a.out &> outfile.txt

# redirect all three to different files:
# (< redirects stdin, 1> stdout, and 2> stderr):
$ ./a.out < infile.txt 1> outfile.txt 2> errorfile.txt

Processes

ps

$ ps aux
image1.png

$ ps aux | grep ./a.out | grep -v grep
-v means inverted choose (反选)

cat /proc/[PID]/maps
image2.png
image.png

avatar
Jialuo Hu
I contribute to my hobby.