Learn Bash - Redirection and Grep

Question Click to View Answer

Write the text "blah" to the file ~/Desktop/motivation.

echo "blah" > ~/Desktop/motivation

The > operator redirects the standard output of a command to a text file (by default, the standard output is directed to the terminal screen).

Open the ~/Desktop/motivation file with a text editor or a program like less or cat to inspect the content.

less ~/Desktop/motivation
cat ~/Desktop/motivation

Now write the text "lolz" to the file ~/Desktop/motivation. Describe what happened to the original content of the ~/Desktop/motivation file.

echo "lolz" > ~/Desktop/motivation

The original content of the ~/Desktop/motivation file has been deleted and the file has been replaced with the string 'lolz'. This is called clobbering and it's something to watch out for because Unix systems will clobber files without any warnings or notifications.

Append the text "that was funny" to the ~/Desktop/motivation file without clobbering it.

echo "that was funny" >> ~/Desktop/motivation

The >> operator does not clobber the existing text in a file, it just appends the text to the bottom of the existing file.

Write the output from the history command to the ~/Desktop/last_500 file.

history > ~/Desktop/last_500

Find all instances of the substring bin in the ~/Desktop/last_500 file.

grep bin ~/Desktop/last_500

grep searches lines of files for regular expression matches and returns the lines that match.

By default, the output of Shell programs is written to the shell. Use a pipe to redirect the output of the history command to the grep command and find all the commands in the history that contain the substring ls.

history | grep ls

Shells typically end with the letters 'sh' (i.e. zsh, csh, etc.). Find all files that end with the string 'sh' in the /bin directory.

ls /bin | grep 'sh$'

'sh$' is the regular expression to find all files that end with the string 'sh'

Return the number of results that are returned by the history command.

history | wc -l

Return a sorted list of all the files in the /bin and /usr/bin directories.

ls /bin /usr/bin | sort

The directories in the $PATH environment variable are typically separated with colons. List all the directories in the $PATH environment variable, but separate them with spaces.

echo $PATH | tr ":" " "

List all the files that are contained in the directories in the path.

ls $(echo $PATH | tr ":" " ")

The code enclosed in $() is executed first and then passed to ls as an argument.