This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 3: Advanced Commands

Pipes and Redirection

face Harry Coppock

Pipes: |

Pipes are an extremely useful functionality in shell as they allow you to pipe outputs from one command into another using the command |.

To demonstrate this here are some examples:

Once again cd /usr/bin/. Lets say you want to view the contents of this directory, one would naturally try ls -l. However, there are so many files that you cannot see most of the contents, try it yourself. Well what we can do is pipe the output of ls -l into the less command allowing us to slowly scroll through the output:

ls -l | less
We could take this one step further, lets assume you are only interested in the files (so not directories) which were last modified in March irrespective of which year.

ls -l | grep Mar | grep "^-........." | less

Redirection: > and >>

The redirection functionality allows us to write or append output from commands to files. Lets explore this through a couple of examples.

echo hello world!
As you can see echo outputs the arguments which it is passed, hence the name. We can use redirection to redirect the outputs from the terminal to a file e.g:

echo hello world! > file1.txt
cat file1.txt

If we repeat the above process with a command like:

echo linux is the best > file1.txt
cat file1.txt
We can see the ‘hello world!’ is overwritten. If you want to append to a file use >> not >

This functionality is commonly used to create requirements.txt files for code repositories which details all the required packages to run the code base. The steps to achieve this are:

python3 -m venv /coolProject/coolProjectEnv           # create a virtual environment
source /coolProject/coolProjectEnv/bin/activate       # activate your virtual environment
pip install pandas                                    # install some packages to demonstrate the below command
pip freeze > requirements.txt                         # save the package requirments to a txt

Then when someone is looking to use your codebase all they need to do create the required environment is:

python3 -m venv myEnv
source myEnv/bin/activate
pip install -r requirements.txt

Redirection can of course be combined with piping. For example:

ls -l | grep Mar | grep "^-........." > file2.txt