How to Redirect Input and Output in Bash
Let us understand redirect input and output in Bash through examples.
ls -l > file.txt
This command lists the files in the current directory in a long format and redirects the output to a file named "file.txt". The contents of "file.txt" will be overwritten if the file already exists.
In [1]:
ls -l > file.txt
let us look at the above file.
In [2]:
cat file.txt | head -1
total 345280
find . -name "*.txt" >> files.txt
This command searches for all files with the ".txt" extension in the current directory and redirects the output to a file named "files.txt". The output will be appended to the file if it already exists.
In [28]:
find . -name "*.txt" >> files.txt
Let us check the content of above file.
In [32]:
cat files.txt | wc -l
5916
There are 5916 .txt files in the current directory
In [37]:
cat files.txt | tail -1
./requirements.txt
sort < unsorted.txt > sorted.txt
This command sorts the contents of a file named "unsorted.txt" and redirects the output to a new file named "sorted.txt".
Let us create a dummy example file.
In [3]:
echo 3 >> unsorted.txt
echo 1 >> unsorted.txt
echo 2 >> unsorted.txt
In [4]:
cat unsorted.txt 3 1 2
Let us sort now.
In [5]:
sort < unsorted.txt > sorted.txt
Let us check the contents now.
In [6]:
cat sorted.txt 1 2 3
grep "error" /var/log/syslog | mail -s "Error Log" email
This command searches the file "/var/log/syslog" for the string "error" and pipes the output to the "mail" command, which sends an email with the subject "Error Log" to the address "email".
command 2> error.log
This command runs the command and redirects the error output to a file named "error.log".
In [25]:
echo 1 2> error.log
1
In [26]:
cat error.log
There is no error in the above the command that is why error.log is empty
command 1&> combined.log
This command runs the command and redirects both standard output and error output to a file named "combined.log".
In [14]:
ech 1= j&> combined.log
Note I intentionally added a typo in the above command. Let us check the output.
In [15]:
cat combined.log
Command 'ech' not found, did you mean:
command 'sch' from deb scheme2c (2012.10.14-1ubuntu1)
command 'ecl' from deb ecl (16.1.3+ds-4)
command 'bch' from deb bikeshed (1.78-0ubuntu1)
command 'ecj' from deb ecj (3.16.0-1)
command 'ecc' from deb ecere-dev (0.44.15-1build3)
command 'ecs' from deb ecere-dev (0.44.15-1build3)
command 'ecp' from deb ecere-dev (0.44.15-1build3)
command 'dch' from deb devscripts (2.20.2ubuntu2)
command 'echo' from deb coreutils (8.30-3ubuntu2)
command 'ecm' from deb gmp-ecm (7.0.4+ds-5)
Try: apt install <deb name>
command > /dev/null
This command runs the command and discards the standard output.
In [7]:
echo 1 > /dev/null