directory

The Shebang line

Execution permission and path

Env command

annotation

Script parameters

The shift command

Getopts command

Configuration item parameter terminator —

The exit command

Command Execution Result

The source command

Alias, alias command


A script, “script,” is a text file that contains a series of commands. The Shell reads this file and executes all the commands in turn as if they were typed directly to the command line. Anything that can be done on the command line can be done with scripts.

The advantage of scripts is that they can be used repeatedly and can be specified for automatic invocation in specific situations, such as when the system is started or shut down.

The Shebang line

The first line of a script usually specifies the interpreter through which the script must be executed. This line begins with #! At the beginning of a character, this character is called a Shebang, so this line is called a Shebang line.

#! The Bash interpreter is /bin/sh or /bin/bash.

#! /bin/sh
# or
#! /bin/bash
Copy the code

#! Spaces between and the script interpreter are ok.

If the Bash interpreter is not in the /bin directory, the script will not execute. To be safe, we could write it like this.

#! /usr/bin/env bash
Copy the code

The above command uses the env command (which is always in the /usr/bin directory) to return the location of the Bash executable. For a detailed description of the env command, see below.

The Shebang line is not required, but is recommended. If the line is missing, you need to manually pass the script to the interpreter. For example, if the script is script.sh and has a Shebang line, you can call the execution directly.

$ ./script.sh
Copy the code

In the example above, script.sh is the name of the script file. Scripts usually use the.sh suffix, though this is not required.

Without a Shebang line, you have to manually pass the script to the interpreter for execution.

$ /bin/sh ./script.sh
# or
$ bash ./script.sh
Copy the code

 

Execution permission and path

As mentioned earlier, the script can be executed directly as long as the Shebang line is specified. One prerequisite for this is that the script must have execution permission. You can run the following command to grant the script execution permission.

Give execute permission to all users
$ chmod +x script.sh

Grant read and execute permissions to all users
$ chmod +rx script.sh
# or
$ chmod 755 script.sh

Give only read and execute permissions to the script owner
$ chmod u+rx script.sh
Copy the code

Script permissions are usually set to 755 (owner has all permissions, others have read and execute permissions) or 700 (only owner can execute).

In addition to execution permissions, when a script is invoked, the script path (such as path/script.sh) needs to be specified. If you place the script in the directory specified by the environment variable $PATH, you do not need to specify a PATH. Because Bash automatically goes to those directories and looks for executable files with the same name.

You are advised to create a ~/bin subdirectory in the home directory to store executable scripts and add ~/bin to $PATH.

export PATH=$PATH:~/bin
Copy the code

Change the environment variable $PATH by adding ~/bin to the end of $PATH. You can add this line to the ~/.bashrc file and reload.bashrc to make this configuration work.

$ source ~/.bashrc
Copy the code

In the future, no matter in any directory, directly enter the file name of the script, the script will be executed.

$ script.sh
Copy the code

The command above does not specify the script PATH because script.sh is in the directory specified by $PATH.

 

Env command

The env command always points to the /usr/bin/env file, or the binary is always in the /usr/bin directory.

#! The /usr/bin/env NAME syntax tells the Shell to look for the first matching NAME in the $PATH environment variable. This is useful if you don’t know the exact path to a command, or if you want to be compatible with other users’ machines.

/usr/bin/env bash returns the location of the bash executable, provided that the bash PATH is within $PATH. Other script files can also use this command. For example, the Shebang line of a Node.js script could be written as follows.

#! /usr/bin/env node
Copy the code

The parameters of the env command are as follows.

  • -i.--ignore-environment: Starts without environment variables.
  • -u.--unset=NAME: Removes a variable from the environment variable.
  • --help: Displays help.
  • --version: Displays the version information.

Here is an example of creating a new Shell without any environment variables.

$ env -i /bin/sh
Copy the code

 

annotation

In Bash scripts, # denotes a comment and can be placed at the beginning or end of the line.

This line is a comment
echo 'Hello World! '

echo 'Hello World! ' The part after the hashmark is also a comment
Copy the code

It is recommended that you use comments at the beginning of the script to explain the function of the current script for future maintenance.

 

Script parameters

When a script is called, the script file name can be followed by arguments.

$ script.sh word1 word2 word3
Copy the code

In the example above, script.sh is a script file, and word1, word2, and word3 are the three arguments.

Inside the script file, you can reference these parameters using special variables.

  • $0: Indicates the name of the script filescript.sh.
  • The $1~$9: corresponds to the first to the ninth parameter of the script.
  • $#: Indicates the total number of parameters.
  • $@: All parameters are separated by Spaces.
  • $*: All parameters, using variables between parameters$IFSValue is delimited by the first character. Default is space, but you can customize it.

If the script has more than nine arguments, the 10th argument can be referenced as ${10}, and so on.

Note that if the command is command-o foo bar, then -o is $1, foo is $2, and bar is $3.

Here is an example of a script reading command line arguments internally.

#! /bin/bash
# script.sh

echo "All parameters:" $@
echo "Number of command-line arguments:" $#
echo '$0 =' $0
echo '$1 =' The $1
echo '$2 =' $2
echo '$3 =' $3
Copy the code

The result is as follows:

$./script.sh a b c All parameters: a b c Number of command line parameters: 3$0 =  script.sh
The $1 =  a
$2 =  b
$3 =  c
Copy the code

The user can enter any number of parameters, and with the for loop, each parameter can be read.

#! /bin/bash

for i in "$@"; do
  echo $i
done
Copy the code

In the example above, $@ returns a list of all the arguments, which is then iterated through using the for loop.

If multiple parameters are enclosed in double quotation marks, they are treated as one parameter.

$ ./script.sh "a b"
Copy the code

In the example above, Bash would consider “a b” a parameter, and $1 would return a b. Note that the return does not include double quotes.

 

The shift command

The shift command changes the script parameters, removing the current first parameter of the script ($1) with each execution, so that the following parameters move forward one bit: $2 becomes $1, $3 becomes $2, $4 becomes $3, and so on.

The while loop, in conjunction with the Shift command, can also read each argument.

#! /bin/bash

echo "There you go$#The parameters"

while [ "The $1"! ="" ]; do
  echo "The rest$#The parameters"
  echo "Parameters:The $1"
  shift
done
Copy the code

In the example above, the shift command removes the current first argument each time, thus iterating through all the arguments through the while loop.

The shift command can take an integer as an argument specifying the number of arguments to remove. The default is 1.

shift 3
Copy the code

The command above removes the first three arguments, making $4 $1.

 

Getopts command

The getopts command is used internally to parse complex script command-line arguments, usually in conjunction with a while loop to extract all of the script’s arguments with a leading conjunction line (-).

getopts optstring name
Copy the code

It takes two arguments. The first argument, optString, is a string that gives all the concatenation line arguments to the script. For example, if a script can have three configuration parameters -l, -h, and -a, only -a can have parameter values, and -l and -h are switch parameters, then the first parameter of getopts is written as lha:, and the order is not important. Note that a is followed by a colon to indicate that the parameter has a parameter value, and getopts specifies that configuration item parameters with parameter values must be followed by a colon (:). The second parameter to getopts, name, is a variable name that holds the currently fetched configuration item parameter, namely l, H, or A.

Here’s an example.

while getopts 'lha:' OPTION; do
  case "$OPTION" in
    l)
      echo "linuxconfig"
      ;;

    h)
      echo "h stands for h"
      ;;

    a)
      avalue="$OPTARG"
      echo "The value provided is $OPTARG";; ?).echo "script usage: $(basename $0) [-l] [-h] [-a somevalue]"2 > &exit1;;esac
done
shift "$(($OPTIND - 1))"
Copy the code

In the example above, the while loop continuously executes the getopts ‘lha:’ OPTION command, each time reading a conjunction line argument (and the corresponding argument value) and entering the body of the loop. The OPTION variable holds the conjunction line argument (that is, L, H, or a) that is currently being processed. If the user enters an unspecified argument (such as -x), then OPTION equals? . The circulatory body uses case judgment to process these four different situations.

If a conjunction line argument has an argument value, such as -a foo, then the environment variable $OPTARG holds the argument value when processing the a argument.

Note that whenever a parameter without a conjunction line is encountered, getopts fails, thus exiting the while loop. For example, getopts can parse command -l foo, but not command foo -l. In addition, getopts can handle the form of multiple conjoined line arguments written together, such as command-lh.

The variable $OPTIND is 1 before getopts begins execution, and then increments by 1 each time it is executed. Waiting until you exit the while loop means that the conjunction line arguments are all processed. $optin-1 is the number of concatenation line arguments that have already been processed. Use shift to remove these arguments and ensure that the following code can process the main arguments of the command with $1, $2, etc.

 

Terminator of configuration item parameter--

If you want to specify a variable as an entity parameter instead of a configuration item parameter, you can use the configuration item parameter terminator –.

$ myPath="~/docs"
$ ls -- $myPath
Copy the code

In the example above, the — mandatory variable $myPath can only be interpreted as an entity parameter (i.e., pathname).

If the variable is not a pathname, an error is reported.

$ myPath="-l"
$ ls -- $myPathLs: cannot be accessed'-l': Does not have that file or directoryCopy the code

In the example above, the variable myPath has a value of -l, not path. However, — forces $myPath to be interpreted only as a path, causing an error “the path does not exist”.

 

The exit command

The exit command is used to terminate the execution of the current script and return an exit value to the Shell.

$ exit
Copy the code

The command above terminates the current script and takes the exit status of the last command as the exit status of the entire script.

The exit command can be followed by an argument, which is the exit status.

# Exit value 0 (success)
$ exit 0

# Exit value 1 (failed)
$ exit 1
Copy the code

On exit, the script returns an exit value. Exit value of the script. 0 indicates normal, 1 indicates an error, 2 indicates incorrect usage, 126 indicates that the script is not executable, and 127 indicates that the command is not found. If the script is terminated by signal N, the exit value is 128 + N. Simply put, any exit value that is not zero is considered an error.

Here’s an example.

if [ $(id -u) != "0" ]; then
  echo "Only root can execute the current script."
  exit 1
fi
Copy the code

In the above example, the id -u command returns the user ID. If the user ID is not equal to 0 (the root user ID), the script exits with an exit code of 1, indicating a failure.

The difference between exit and return is that the return command exits the function and returns a value to the caller, while the script continues to execute. Exit is the exit of the entire script. If exit is called within a function, it exits the function and terminates script execution.

 

Command Execution Result

After the command is executed, a return value is displayed. 0 indicates that the execution is successful. A value other than 0 (usually 1) indicates that the execution fails. Environment variable $? The return value of the previous command can be read.

This allows you to determine the result of command execution in the script.

cd $some_directory
if [ "$?" = "0" ]; then
  rm *
else
  echo "Unable to switch directories!"> 1 & 2exit 1
fi
Copy the code

In the preceding example, if the CD $some_directory command is executed successfully (the return value is 0), the files in the directory will be deleted. Otherwise, the script will exit, and the return value of the entire script will change to 1, indicating that the execution fails.

Since if can directly determine the execution result of the command and execute the corresponding operation, the above script can be rewritten as follows.

if cd $some_directory; then
  rm *
else
  echo "Could not change directory! Aborting."> 1 & 2exit 1
fi
Copy the code

More concise writing is to use two logical operators && (and) and | | (or).

Step 2 will be executed only if step 1 succeeds
cd $some_directory && rm *

If the first step fails, the second step is executed
cd $some_directory || exit 1
Copy the code

 

The source command

The source command is used to execute a script, usually used to reload a configuration file.

$ source .bashrc
Copy the code

The best feature of the source command is that it executes the script in the current Shell, unlike creating a new subshell when executing the script directly. Therefore, the source command does not need the export variable when executing the script.

#! /bin/bash
# test.sh
echo $foo
Copy the code

The script above prints the value of the $foo variable.

Create a new variable foo for the current Shell
$ foo=1

Print 1
$ source test.sh
1

Print an empty string
$ bash test.sh
Copy the code

In the example above, the current Shell variable foo is not exported, so the direct execution cannot read it, but the source execution can.

Another use of the source command is to load external libraries inside the script.

#! /bin/bash

source ./lib.sh

function_from_lib
Copy the code

The above script internally loads an external library using the source command, and then uses the functions defined by the external library inside the script.

Source has a short form that uses a dot (.) To represent.

$ . .bashrc
Copy the code

 

Alias, alias command

Using the alias command, you can specify an alias for a command. Here is the format of alias.

alias NAME=DEFINITION
Copy the code

In the above command, NAME is the NAME of the alias and DEFINITION is the original command corresponding to the alias. Note that there must be no Spaces on either side of the equal sign, otherwise an error will be reported.

A common example is to alias the grep command search.

alias search=grep
Copy the code

Alias can also be used to specify a shorter alias for a long command. Here is the command to define a today by alias.

$ alias today='date +"%A, %B %-d, %Y"'$Today Monday, January 6, 2020Copy the code

Sometimes, you can specify an alias for the rm command to prevent file deletion by mistake.

$ alias rm='rm -i'
Copy the code

The preceding command specifies that the rm command is rm -i, and the user is asked to confirm the deletion each time.

Aliases defined by alias can also accept arguments that are passed directly to the original command.

$ alias echo='echo It says: '
$ echo hello world
It says: hello world
Copy the code

In the example above, the alias defines the first two parameters of the echo command, which is equivalent to modifying the default behavior of the echo command.

Once you specify an alias, you can use it just like any other command. In general, common aliases are written at the end of ~/.bashrc. In addition, you can only define aliases for commands; aliases for other parts (such as long paths) are not valid.

Call the alias command directly to display all aliases.

$ alias
Copy the code

Using the unalias command, you can remove an alias.

$ unalias lt
Copy the code

 

The next section of the Bash script tutorial reads the command