Kaigai Blog living abroad in my twenties

【My Study Note】Redirection

Commands Programming

Redirection


The basic workflow of any Linux command is that it takes an input and gives an output. The standard input device is the keyboard. The standard output device is the screen. With redirection, you can change the standard input and/or output. There are three types of IO or input/output redirections.

通常、サーバー上での作業時には端末を開いて作業を行います。実行されたコマンドの出力は概ねコンソール画面上に表示されますが、運用上の要件により、作業内容のログや過去の出力内容などを取っておきたいことがあります。そんな時に役立つのがリダイレクトです。

The shell keeps a reference of standard input, output, and error by a numbering system. The zero is for standard input, one is for standard output, and two is for standard error.

Standard Input

Taking input normally refers to a user typing information from the keyboard. We use the “<" sign for user input. The cat command can be used to record user input and save it to a file. How do we take input and store it in a file such as a .TXT file? Cat command is actually set up to take in input. On your terminal, you type the cat command, followed by a "<" sign, and then follow it with the name of the input file. In this scenario, input.txt, press Enter. Now you can add text to the text file created. At the end of the text, press Enter. Next, press Control D to tell the cat command that's the end of the file.

cat > input.txt
This is me adding some text from the keyboard.

To output the contents of the file, enter cat, followed by a less than sign, followed by input.txt, press Enter.

cat < input.txt
// Output: This is me adding some text from the keyboard.

Standard Output

A lot of the commands we have already used, for example, ls, send their output to a special file called the standard output. Output direction is handled with a ">" sign. IO allows us to use redirection to control where the output goes.

echo "hello" > stdout.txt
ls -l
// Output: -rw-r--r--   1 fukatanaoya  admin     6 Nov 22 12:43 stdout.txt
cat stdout.txt
// Output: hello

Standard Error

Errors occur when things go wrong. When using redirection, you also have to specify that the error should be written to a file. You can do that by explicitly setting "2>" and you can also combine it with the standard output of "2>&1" to print both the standard output and error if any occursn (So either way if there's a error or not, you can output it in a file).

MacBook-Air ~ % ls /bin/usr > error.txt
ls: /bin/usr: No such file or directory
MacBook-Air ~ % ls /bin/usr 2> error.txt
MacBook-Air ~ % cat error.txt
ls: /bin/usr: No such file or directory
MacBook-Air ~ % ls /bin/usr > error.txt 2>&1
MacBook-Air ~ % cat error.txt
ls: /bin/usr: No such file or directory