Logo of the site

My cheatsheet

Bash cheatsheet

This is a quick reference cheat sheet for understanding and writing Bash commands.

# Getting started

Introduction

Bash, or the Bourne-Again SHell, is a CLI that was created in 1989 by Brian Fox as a free software replacement for the Bourne Shell. A shell is a specific kind of CLI. Bash is open source. In most ways Zsh is an exact replacement for Bash, so there is no need to switch over or install Bash instead.

When using the command line, we refer to folders as directories. Files and directories on your computer are organized into a filesystem.

# Navigation

Basic navigation

Clear terminal

$ clear

Current directory’s files and directories

$ ls

Output the name of the directory you are currently in, called the working directory.

$ pwd

Chain options

List all contents, including hidden files and directories, in long format, ordered by the date and time they were last modified.

$ ls -alt

Options:

  • -a - lists all contents, including hidden files and directories (shown starting with a .)
  • -l - lists all contents of a directory in long format, as well as the file permissions. Each column means:
    • Access rights. These indicate the read, write, and execute permissions on the file or directory allowed to the owner, the group, and all users. You can read more about file permissions.
    • Number of hard links. This represents the number of hard links to the file or directory. This number includes the parent directory link (...) and current directory link (.).
    • The username of the file’s owner. Here the username is cc.
    • The name of the group that owns the file. Here the group name is eng.
    • The size of the file in bytes.
    • The date & time that the file was last modified.
    • The name of the file or directory.
  • -t - orders files and directories by the time they were last modified.

Result of ls -l

$ ls -l
drwxr-xr-x 5  cc  eng  4096 Jun 24 16:51  action
drwxr-xr-x 4  cc  eng  4096 Jun 24 16:51  comedy
drwxr-xr-x 6  cc  eng  4096 Jun 24 16:51  drama
-rw-r--r-- 1  cc  eng     0 Jun 24 16:51  genres.txt

Move between folders

Change the working directory

$ cd directory_name

Move up one folder

$ cd ..

Move up two or more folders

$ cd ../..

Move across multiple directories with a single command, we can provide cd a relative path to the memory/ directory as an argument

$ cd 2015/jan/memory

The last two points can be chained together (move up then move to the directory)

$ cd ../2014

Create folder

The mkdir command stands for “make directory”. It takes in a directory name as an argument and then creates a new directory in the current working directory.

$ mkdir newDirectory_name
$ mkdir relative_path

# File manipulation

Create file

Create a new file inside the working directory

$ touch keyboard.txt

Remove files

The rm command deletes files and directories.

$ rm unwanted_file.txt
$ rm -r unwanted_directory

Print the content of a file

The cat command outputs in the terminal the contents of a specified file

$ cat hello_cli.txt

Create a new file named hello_cli.txt and add Hello Command Line to that file

$ echo "Hello Command Line" >> hello_cli.txt

Copy files

Make a copy of a file

$ cp source.txt destination.bak

Copy multiple files to a directory

$ cp file1.txt folder/file2.txt my_directory
$ cp * my_directory
$ cp *.txt my_directory
$ cp w*.txt my_directory

Move files from a directory to another

$ mv my_file.txt my_directory/
$ mv my_file.txt .

# Redirection

Introduction

Through redirection, you can direct the input and output of a command to and from other files and programs, and chain commands together in a pipeline.

$ echo "Hello"

The echo command accepts the string “Hello” as standard input, and echoes the string “Hello” back to the terminal as standard output.

Standard I/O

  • stdin: information inputted into the terminal through the keyboard or input device.
  • stdout: the information outputted after a process is run.
  • stderr: an error message outputted by a failed process.

Redirection Operators

Redirect standard output to a file (overwrites content):

$ echo "Hello" > hello.txt

Append standard output to a file:

$ cat forests.txt >> hello.txt

Use a file as standard input:

$ cat < deserts.txt

That in this case is the same as:

$ cat deserts.txt

Pipe standard output to another command:

$ cat volcanoes.txt | wc

Multiple pipes can be chained together:

$ cat volcanoes.txt | wc | cat > count.txt

Sort and Uniq

Sort standard input alphabetically:

$ sort continents.txt

Example: Sort and redirect to a new file:

$ cat glaciers.txt | sort > sorted-glaciers.txt

Remove duplicate lines:

$ sort deserts.txt | uniq

Sed

Substitute text in a file:

$ sed 's/snow/rain/' forests.txt

Substitute text globally in a file:

$ sed 's/snow/rain/g' forests.txt

Rewrite the actual file:

$ sed -i 's/snow/rain/g' forests.txt

Grep

Search for a pattern in a file (case-insensitive):

$ grep -i America continents.txt

Search recursively in a directory:

$ grep -R Arctic /home/ccuser/workspace/geography

Output only filenames with matched results:

$ grep -Rl Arctic /home/ccuser/workspace/geography

# Environment

nano

nano is a command line text editor. It works the same way as a desktop text editor like TextEdit or Notepad, except that it is accessible from the command line and only accepts keyboard input.

$ nano hello.txt

The command nano hello.txt opens a new text file named hello.txt in the nano text editor.

Hello, I am nano is a text string entered in nano at the line indicated by the cursor.

The menu of keyboard commands at the bottom of the window allows us to save changes to hello.txt and exit nano.

Bash Profile

A bash profile is a file used to store environment settings for your terminal. On most computer systems, the file is in the home directory and is accessible by the name .bash_profile.

When you edit the bash profile, you can add commands to execute every time a new terminal session is started.

To activate the changes made in .bash_profile for the current session, use:

$ source .bash_profile

Absolute path of .bash_profile:

~/.bash_profile

If not existent, a new one has to be created.

Alias

The alias command allows you to create keyboard shortcuts, or aliases, for commonly used commands.

Here, alias pd="pwd" creates the alias pd for the pwd command, which is then saved in the bash profile. Please note, no spaces are allowed before and after the = symbol.

$ alias pd="pwd"

The pd alias will be available each time we open a new terminal session, and the output of pd will be the same as the pwd command.

source .bash_profile will make the alias pd available in the current session.

Environment Variables

Environment variables are variables that can be used across commands and programs and hold information about the environment.

Example:

$ export USER="Jane Doe"

The line USER="Jane Doe" sets the environment variable USER to a name “Jane Doe”. Usually the USER variable is set to the name of the computer’s owner.

The line export makes the variable available to all child sessions initiated from the session you are in. This is a way to make the variable persist across programs.

At the command line, the command echo $USER returns the value of the variable. Note that $ is always used when returning a variable’s value. Here, the command echo $USER returns the name set for the variable.

Env

The env command stands for “environment,” and returns a list of the environment variables for the current user.

The env command returns a number of variables, including PATH, PWD, PS1, and HOME. To select the value of a particular environment variable, let’s say PATH, you can use the following command:

$ env | grep PATH

PATH

PATH is an environment variable that stores a list of directories separated by a colon.

$ echo $PATH

Returns:

/home/ccuser/.gem/ruby/2.0.0/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/usr/sbin:/sbin:/bin

Each directory contains scripts for the command line to execute. The PATH variable simply lists which directories contain scripts.

For example, many commands we’ve learned are scripts stored in the /bin directory.

$ /bin/pwd

Returns the same as:

$ pwd

PS1

PS1 is an environment variable that defines the makeup and style of the command prompt. A space must be used after the desired symbol.

$ export PS1=">> "

export PS1=">> " sets the command prompt variable and exports the variable. Here we change the default command prompt from $ to >>.

After using the source command, the command line displays the new command prompt.

>>

HOME

The HOME variable is an environment variable that displays the path of the home directory ~. You can specify and change the HOME variable if needed, but in most cases this is not necessary.

$ echo $HOME

# Examples

Find empty .txt files

List .txt files with no content across all directories and save the listing in empty_files.txt in the todo/ directory.

$ wc -l */*.txt | grep 0 > todo/empty_files.txt

The -l option of the wc command counts the number of lines.