Friday 15 July 2022

Unix Shell Redirection

Redirection operators > and >> can write into a file or a device.

  • > will overwrite existing file or crate a new file
  • >> will append text to existing file or create a new file

 

Example: redirecting command output into a file

$ touch temp.txt
$ echo "Hello, world!" > temp.txt
$ cat temp.txt
Hello, world!
$ echo "Hello, world!" > temp.txt
$ cat temp.txt
Hello, world!
$ echo "Hello, world!" >> temp.txt
$ cat temp.txt
Hello, world!
Hello, world!

Here are examples where redirect operators crated new files:

$ echo "Hello, world!" > temp2.txt
$ cat temp2.txt
Hello, world!
$ echo "Hello, world!" >> temp3.txt
$ cat temp3.txt
Hello, world!

Devices/files:

0 - stdin (standard input)
1 - stdout (standard output)
2 - stderr (error message output) 
/dev/null - special device (null device) which discards any input

 

Example: discarding command output messages (including error messages)

command > /dev/null 2>$1

2>$1 redirects stderr into stdout and > /dev/null redirects stdout into null device.

More compact version of the above line is:

command  &> /dev/null

&> /dev/null redirects both stdout and stderr into null device.


References:


What does “>” do vs “>>”?

No comments: