Bash is the default command-line environment (Shell) on most Linux distributions. Its syntax is simple and can conveniently operate native commands on Linux-like systems, suitable for automation work such as backups and quick deployments.

Bash is the default command-line environment (Shell) on most Linux distributions. Usually, the command-line commands we talk about are executed in Bash.

Installation

Installing Bash software:

  • macOS

    No installation required, Bash comes pre-installed. The “Terminal” program can execute Bash scripts.

  • Windows

    Download Git client, which will install a Bash program when installing Git client. After installation, find the Bash program in the Start menu.

  • Linux

    No installation required, Bash comes pre-installed. If using a graphical interface, use the “Terminal” program to execute Bash scripts; in command-line interface, you directly enter the Bash program.

Comments

In Bash scripts, # represents comments. Strings after the # symbol will be ignored.

First Script

Let’s open Bash and execute a script in the command line to display files under the root path.

$ ls /  # Display files under root path. Bash scripts use # symbol for comments, characters after # will be ignored
bin   data  etc   opt

Note: In example code, each line starting with $ indicates the current script execution user is a non-root account. Lines starting with # indicate the script execution user is a root user.

When copying to your own command line for execution, only copy the part after the $ symbol.

ls is a command (i.e., a program) in Linux used to list files under a path.

Execution Process

The most important point to understand about Bash scripts is: Each script line is first expanded, then executed.

Expansion can be simply understood as replacement. Let’s change the above command to display files under the user’s home path:

ls ~

The execution process is:

  1. First expansion: Assuming the username is bob, ~ will be replaced with /home/bob.
  2. Then execution: ls /home/bob

This is called tilde expansion. There are many other types of expansions that we will explain gradually.

Variable Expansion

There are two types of variables in Bash: environment variables and custom variables.

We can use the echo command to print variable values, similar to the print function in other languages.

Environment Variables:

Environment variables are predefined variables when Bash starts. They can be used directly.

Add $ symbol before the variable name to reference the variable.

$ echo $HOME # HOME variable represents the user's home path
/home/bob

The execution process expands $HOME to /home/bob through parameter expansion, then executes.

Custom Variables:

The following example defines a variable a and prints its value.

$ a=1 # Define a variable a. Note: no spaces allowed on either side of the equal sign
$ echo $a # Print the value of variable a
1

Subcommand Expansion

We can execute a subcommand first in one line command, then execute this command. The format is $(sub command).

As in the following command, first execute ls ~, then execute echo to print the subcommand return result.

echo $(ls ~)

Loop Statements

Mainly use two types of loops: while loop and for loop. While loop involves condition judgment, which we’ll discuss after learning conditions. Let’s first talk about for loop iteration. For loop takes “elements” sequentially from an “element list”.

From here on, we start involving multi-line command scripts. For multi-line scripts, in interactive command line, after pressing Enter, the prompt > allows continued editing, rather than direct execution.

files=$(ls ~)      # Subcommand expansion, and assign to files variable
for file in $files # Take each file from files variable in turn, assign to variable file.
do                 # do indicates loop body start
  echo $file        # Statements to execute each loop
done               # done indicates loop body end

Conditional Statements

Conditional statements in Bash are quite different from other programming languages. Its conditional statements need to use the test command for judgment.

The format of conditional statements is as follows:

if test-commands; then
  consequent-commands;
[elif more-test-commands; then # elif and else branches are optional
  more-consequents;]
[else alternate-consequents;]
fi

if is followed by conditional statements (test-commands), executing different conditional branches based on the truth value of the conditional statements. As shown in the following example, test has many usages. For detailed usage, check here.

if test 1 -ne 2;then # Judge 1 is not equal to 2, here judgment is true, execute if branch
  echo Condition is true
else
  echo Condition is false
fi

Another common usage is to judge whether a command executed successfully, as shown in the following example.

echo Execute some command # After we execute some command, we need to judge whether it executed successfully in the script
if test $? -eq 0; then 
# $? is the return value of the previous command, -eq 0 judges whether the previous command return value equals 0. Command returns 0 indicates success, returns 1 indicates failure
 echo Command execution failed
fi

The test command has two other writing methods, but essentially they all call the test command for judgment. [ is a simplification of test, so [ needs to be immediately followed by a space, otherwise it will report an error.

# Single bracket writing
if [ 1 -ne 2 ];then
fi

# Double bracket writing
if [[ 1 -ne 2 ]];then
fi

References