Use streams, pipes and redirects

From Mintarc Forge

Redirecting standard input, output, and error

< : Redirect input from a file Example: sort < unsorted.txt

  • This reads the contents of unsorted.txt as input for the sort command.

Redirect output to a file (overwrite)

Example: ls -l > file_list.txt

  • This writes the output of ls -l to file_list.txt, overwriting existing content.

Redirect output to a file (append)

Example: echo "New line" >> log.txt

  • This appends "New line" to the end of log.txt.

2>&1 : Redirect stderr to stdout

Example: command > output.txt 2>&1

  • This redirects both stdout and stderr to output.txt.

Piping output between commands:

| : Pipe output of one command to another

Example: cat file.txt | grep "error" | wc -l

  • This counts the number of lines containing "error" in file.txt.

Using output as arguments:

xargs : Build and execute command lines from standard input

Example: find . -name "*.txt" | xargs rm

  • This finds all .txt files and removes them.

Sending output to both stdout and a file:

tee : Read from stdin and write to stdout and files

Example: echo "Hello" | tee output.txt

  • This displays "Hello" on the screen and writes it to output.txt.