Advanced Usage

More Syntax

Files are pattern-matched with regular expressions. The most common pattern is the wildcard *.

ls *.txt # Lists all files that end with `.txt`

Multiple command are run together with ;, && and ||. The conjunction ; runs both commands. The conjunction && runs the second command only if the first command succeeds. The conjunction || runs the second command only if the first command fails. These can be combined indefinitely.

echo "Hello"; echo "World"; echo "!" # Run three commands

# OUTPUT:
# Hello
# World
# !

The output is redirected to a file with >. Errors is redirected to a file with 2>. The directory /dev/null is a placeholder to discard the output.

# Write "Hello World!" in `output.txt` and ignore errors
echo "Hello World!" > output.txt 2> /dev/null

Both > and 2> rewrite the file if it already exists. To append instead, use >> and 2>>.

The output of a command can be piped to another command with |. If the previous command outputs multiple items, then use xargs to pass them as arguments to the next command.

ls | wc -l # Count the files

Variables and the Environment

Variables are set in bash with =. They are retrieved with $.

greeting="Hello World!"
echo $greeting

# OUTPUT:
# Hello World!

Environment variables are variables for the shell session that are seen by all child processes. The command printenv prints the environment variables.

The command export sets environment variables. For example, the command export PATH=$PATH:<new-directory> adds a new directory to the environment variable $PATH. The environment variable $PATH is the list of directories that are searched for executables.

Most environment variables are set for all shell sessions by specifying them in the file .bashrc in the home directory. This file is sourced automatically for every shell session.

Note

By convention, variable names are all lower case if they are local to one file or session. And, variables names are all upper case if they are used across files or are environment variables.

The variable $? is the exit code of the last command. It is 0 if the last command exited without errors. Any other integer means that it exited with errors.

Scripts

Bash can be written in a file and ran with program bash. The file extension of a shell file is .sh. In such files, it may make sense to use more complicate behavior such as loops. For example, if the next code block is in the file script.sh, then the command bash script.sh runs it.

for num in {1..5}
do
    if (( num % 2 == 0 ))
    then
        echo "$num is even"
    else
        echo "$num is odd"
    fi
done
bash script.sh

# OUTPUT:
# 1 is odd
# 2 is even
# 3 is odd
# 4 is even
# 5 is odd

Note

The command bash runs a shell file in a subprocess. The command source sources a shell file. To source a file means that its defined variables persistently exist in the current shell session. When the command bash runs a file, any variables in the file are local to it.