Basic knowledge
1.1 Interpreter
#!/bin/bash
It is called shebang or sha-bang, hashbang. is a special character sequence, composed of the pound sign "#" and the exclamation mark "!", which is placed at the beginning of the first line of the script file. In Linux and Unix-like operating systems, this character sequence is used to specify the interpreter path to the script file. When the first line of a script file contains shebang, the operating system will pass all parameters after the path to the specified interpreter when executing the file, allowing it to explain the execution of the script.
When the system runs a script, it first checks the shebang line of the script, then finds the specified interpreter, and passes the script to it for execution. If the shebang line does not exist or is incorrect in format, the system will treat the script as a normal text file and cannot execute the script. Common interpreters include Bash shell, Python, Perl, etc. You can use the corresponding path to specify the interpreter. For example,#!/usr/bin/python
Indicates that scripts are executed using a Python interpreter.
If a file does not have a shebang line, the system does not know which interpreter to use to execute it. At this point, if the file has executable permissions (for example, 755), the system will execute it as a shell script, using the default shell interpreter (in most Unix/Linux systems, this is the Bash shell).
Shell script is a programming language that can be used to write automated tasks, batch processing of data, system management, etc. on Unix/Linux systems. Here are the basics of shell scripts:
1.2 Variables
Used to store data, can be used=
to assign values, for examplename="kite"
。
1.3 Parameters
Shell scripts can receive parameters passed in from the command line and use$1
、$2
cited by variables, e.g.$1
Indicates the first parameter. This part will give detailed examples.
1.4 Conditional Statement
useif
Statements to implement conditional judgment, for example:
# Script content [Use positional parameters]#!/bin/bash if [ $1 -gt 18 ]; then echo "You are an adult." else echo "You are not an adult yet." fi # Script Call./ 19
1.5 Loop statement
usefor
andwhile
Statements to implement loops, for example:
# for statementfor i in 1 2 3 4 5; do echo $i done # while statement [Variables were used]i=0 while [ $i -lt 10 ]; do echo $i i=$((i+1)) done
1.6 Function
usefunction
or()
Define a function, for example:
# Note that the definition and call of the function are inside the scriptfunction sayHi { echo "Hello, $1!" } sayHi "Kite"
1.7 Input and output
useecho
Command output text, useread
The command reads user input, for example:
# read command will wait for inputecho "What's your name?" read name echo "Hello, $name!"
1.8 Command execution
Use backticks or dollar signs to execute the command and assign the result to the variable, for example:
today=`date +%Y-%m-%d` echo "Today is $today"
1.9 Operator
Shell scripts support arithmetic, string and logical operations, such as:
# arithmetic operationsnum=$((1+2)) echo $num # string operationif [ "$name" == "John" ]; then echo "Hello, John!" fi # Logical operationsif [ $age -gt 18 ] && [ $gender == "male" ]; then echo "You are a man." fi
The above is the basic knowledge of shell scripts. If you master this knowledge, you can write simple scripts to automate tasks. Further learning can master the advanced usage of shell scripts, such as regular expressions, pipelines, redirection, process control, etc.
2. Parameter passing
2.1 Position parameters
In shell scripts, positional parameters can be used to pass information. They can be accessed using 1, 1, 1, 2, $3, etc. For example:
#!/bin/bash echo "The first argument is $1" echo "The second argument is $2"
When executing the script on the command line, two parameters can be passed, as follows:
$ ./ hello world
Output:
The first argument is hello
The second argument is world
2.2 Special variables
The shell provides many special variables to pass additional information, such as:
-
$0
: Indicates the script name. -
$#
: Indicates the number of parameters passed to the script. -
$@
: A list of all parameters passed to the script. -
$?
: Indicates the return value of the previous command.
This also explains why the positional parameter starts from 1.$0
It is often used in logs to indicate the name of the currently executed script.
For example:
#!/bin/bash echo "The script name is $0" echo "The number of arguments is $#" echo "The arguments are $@" echo "The return value of the last command is $?"
When executing the script on the command line, you can pass any number of parameters, as shown below:
$ ./ a b c
Output:
The script name is ./
The number of arguments is 3
The arguments are a b c
The return value of the last command is 0
2.3 Environment variables
Environment variables can be used to pass information. In shell scripts, you can use $VAR to access environment variables. For example:
#!/bin/bash echo "The value of HOME is $HOME" echo "The value of PATH is $JAVA_HOME"
When executing the script on the command line, the value of the environment variable is output as follows:
$ ./ The value of HOME is /root The value of PATH is /usr/local/java/jdk1.8.0_241
Get environment variables in the script to verify the execution environment.
2.4 Named Parameters
2.4.1 getopts
getopts
It is a command line parameter processing tool that comes with Bash shell. Its syntax is relatively simple and only supports processing single letter options, such as-a
、-b
wait.getopts
Only short options can be processed, that is, only one letter can be used to represent options. If you want to deal with long options, you need to write more code. in addition,getopts
When processing command line parameters, the options and parameters will be processed separately, and continuous options cannot be processed, for example-abc
。
# Test script#!/bin/bash while getopts n:a:g: opt do case "${opt}" in n) name=${OPTARG};; a) age=${OPTARG};; g) gender=${OPTARG};; esac done echo "NameVal: $name"; echo "AgeVal: $age"; echo "GenderVal: $gender";
# Script Call./ -n Kite -a 18 -g f NameVal: Kite AgeVal: 18 GenderVal: f
2.4.2 getopt
getopt
It is a command line parameter processing tool in the GNU tool set. It supports more options and syntax, can handle short and long options, and can handle continuous options.getopt
grammar comparisongetopts
More complex, it requires specifying an option string containing all supported options and parameters.getopt
Save parsed options and parameters in an array, and you need to process this array in your code.
getopt
The command has the following parameters:
-
-o
: Specify single-character options. No separator is required between options. -
--long
: Specify the long option. Comma separated between long options. -
:
: Add a colon after the option to indicate that the current option requires parameter values. -
--
: Split options and parameters. -
"$@"
: means to pass all command line parameters as a string togetopt
Order.
options=$(getopt -o n:a:g:p --long name:,age:,gender:,print -- "$@")
Command line options and parameters will be parsed, and the converted options and parameters will be stored in variablesoptions
middle. This variable is usually passed to aeval
Commands are processed, for example:
eval set -- "$options"
# Test script#!/bin/bash # parse command line parametersoptions=$(getopt -o n:a:g:p --long name:,age:,gender:,print -- "$@") eval set -- "$options" # Extract options and parameterswhile true; do case $1 in -a | --age) shift; age=$1 ; shift ;; -n | --name) shift; name=$1 ; shift ;; -g | --gender) shift; gender=$1 ; shift ;; -p | --print) print=true; shift ;; --) shift ; break ;; *) echo "Invalid option: $1" exit 1 ;; esac done # Check variablesif [ -z "$age" ]; then echo "Error: age is required" exit 1 fi if [ -z "$name" ]; then echo "Error: name is required" exit 1 fi if [ -z "$gender" ]; then echo "Error: gender is required" exit 1 fi # determine switch optionsif [ "$print" = true ]; then echo "NameVal: $name; AgeVal: $age; GenderVal: $gender"; fi
# Script call (long option)./ --name Kite --age 18 --gender f -p NameVal: Kite; AgeVal: 18; GenderVal: f # Script call (single character option)./ -n Kite -a 18 -g f -p NameVal: Kite; AgeVal: 18; GenderVal: f
3. Summary
It is also very powerful if you can flexibly use shell scripts.
The above is the detailed description of the four examples of the shell script passing parameters. For more information about the shell script passing parameters, please pay attention to my other related articles!