Bash Redirection
There are three file descriptors namely stdin, stdout and stderr. These are known as standard input, standard output and standard error respectively.
- 2>&1 # Redirects stderr to stdout.
- 1>filename
# Redirect stdout to file "filename."
- 1>>filename
# Redirect and append stdout to file "filename."
- 2>filename
# Redirect stderr to file "filename."
- 2>>filename
# Redirect and append stderr to file "filename."
- &>filename
# Redirect both stdout and stderr to file "filename."
- x>y
# "x" is a file descriptor, which defaults to 1, if not explicitly set.
| Redirection |
Description |
Example |
| redirect stdout to a file |
The output of a program will be written to the specified file |
ls -l > out.txt |
| redirect stderr to a file |
The stderr output will be written to the specified file |
grep da * 2> grep-errors.txt |
| redirect stdout to a stderr |
The stderr ouput of a program will be written to the same filedescriptor than stdout. |
grep da * 1>&2 |
Example:
#!/bin/bash
echo "test";
echod "Wrong command";
running above file (./a)
w3user@ubuntu-a:~$ ./a
test
./a: line 4: echod: command not found
w3user@ubuntu-a:~$
now redirecting output (stdout, 1) to a file
w3user@ubuntu-a:~$ ./a
test
./a: line 4: echod: command not found
w3user@ubuntu-a:~$
now redirecting output (stderr, 2) to a file
w3user@ubuntu-a:~$ ./a 2> out
test
w3user@ubuntu-a:~$
w3user@ubuntu-a:~$cat out
./a: line 4: echod: command not found
w3user@ubuntu-a:~$
you can see above (out file) has stderr...