Linux [Script 04] 4 ways of shell script passing parameters (positional parameters, special variables, environment variables and named parameters) example description

Four ways to pass parameters in script

    • 1. Shell basic knowledge
      • 1.1 Interpreter
      • 1.2 Variables
      • 1.3 parameters
      • 1.4 Conditional Statements
      • 1.5 Loop Statements
      • 1.6 Functions
      • 1.7 Input and output
      • 1.8 Command Execution
      • 1.9 Operators
    • 2. Parameter passing
      • 2.1 Positional parameters
      • 2.2 Special variables
      • 2.3 Environment variables
      • 2.4 Named parameters
        • 2.4.1 getopts
        • 2.4.2 getopt
    • 3. Summary

Shell scripting is a command language that can be used to automate various tasks. In the script, we can pass information through parameters, so that the script can perform specific operations based on the information. This article will explain how to pass parameters in shell scripts, including positional parameters, special variables, environment variables and named parameters.

1. Basic knowledge of Shell

1.1 Interpreter

#!/bin/bash is called shebang or sha-bang, hashbang. Is a special sequence of characters, composed of pound sign “#” and exclamation mark “!”, placed at the beginning of the first line of the script file. On Linux and Unix-like operating systems, this sequence of characters is used to specify the interpreter path for script files. When the first line of a script file contains a shebang, the operating system will pass all the parameters after the path to the specified interpreter when executing the file, and let it interpret and execute the script.

When the system runs a script, it first checks the script’s shebang line, then finds the specified interpreter, and passes the script to it for execution. If the shebang line does not exist or is malformed, the system treats 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 means to use the Python interpreter to execute the script.

If a file doesn’t have a shebang line, the system doesn’t know which interpreter to use to execute it. At this point, if the file has executable permissions (such as 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 data processing, system management, etc. on Unix/Linux systems. Here are the basics of shell scripting:

1.2 Variables

For storing data, you can use = to assign values, such as name="kite".

1.3 Parameters

Shell scripts can receive parameters passed in from the command line, and use variables such as $1 and $2 to refer to them. For example, $1 represents the first parameter. Chapter 2 of this part will give detailed examples.

1.4 Conditional statement

Use the if statement to implement conditional judgment, for example:

# script content script.sh [use positional parameters]
#!/bin/bash
if [ $1 -gt 18 ]; then
    echo "You are an adult."
else
    echo "You are not an adult yet."
the fi
# script call
./script.sh 19

1.5 Loop statement

Use for and while statements to implement loops, for example:

# for statement
for i in 1 2 3 4 5; do
    echo $i
done

# while statement [using variables]
i=0
while [ $i -lt 10 ]; do
    echo $i
    i=$((i + 1))
done

1.6 Function

Use function or () to define functions, for example:

# Note that the definition and call of the function are all inside the script
function sayHi {<!-- -->
    echo "Hello, $1!"
}
say Hi "Kite"

1.7 Input and output

Use the echo command to output text, and use the read command to read user input, for example:

# read command will wait for input
echo "What's your name?"
read name
echo "Hello, $name!"

1.8 Command execution

Use backticks or dollar signs to execute a command and assign the result to a variable, for example:

today=`date + %Y-%m-%d`
echo "Today is $today"

1.9 Operators

Shell scripts support arithmetic operations, string operations, and logical operations, for example:

# Arithmetic operations
num=$((1 + 2))
echo $num

# String operations
if [ "$name" == "John" ]; then
    echo "Hello, John!"
the fi

# logic operation
if [ $age -gt 18 ] & amp; & amp; [ $gender == "male" ]; then
    echo "You are a man."
the fi

The above is the basic knowledge of Shell scripts. After mastering this knowledge, you can write simple scripts to automate tasks. Further study can master the advanced usage of Shell scripts, such as regular expressions, pipelines, redirection, process control, etc.

2. Parameter passing

2.1 Positional parameters

In shell scripts, positional parameters can be used to pass information. They can be accessed using $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:

$ ./script.sh hello world

output:

The first argument is hello
The second argument is world

2.2 Special variables

The shell provides a number of special variables to pass additional information, such as:

  • $0: indicates the script name.
  • $#: Indicates the number of parameters passed to the script.
  • $@: Indicates a list of all parameters passed to the script.
  • $?: Indicates the return value of the previous command.

This also explains why positional parameters start from 1, and $0 is often used in logs to indicate the name of the currently executing 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, any number of parameters can be passed, as follows:

$ ./script.sh a b c

output:

The script name is ./script.sh
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, environment variables can be accessed in the form of $VAR. For example:

#!/bin/bash
echo "The value of HOME is $HOME"
echo "The value of PATH is $JAVA_HOME"

When the script is executed on the command line, the value of the environment variable is output as follows:

$ ./script.sh
The value of HOME is /root
The value of PATH is /usr/local/java/jdk1.8.0_241

Obtain environment variables in the script to check the execution environment.

2.4 Named parameters

2.4.1 getopts

getopts is a command line parameter processing tool that comes with the Bash shell. Its syntax is relatively simple, and it only supports processing single letter options, such as -a, -b etc. getopts can only handle short options, that is, only one letter can be used to represent options. If you want to process long options, you need to write more code. In addition, when getopts processes command line parameters, it will process options and parameters separately, and cannot process continuous options, such as -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
./script.sh -n Kite -a 18 -g f
NameVal: Kite
AgeVal: 18
GenderVal: f

2.4.2 getopt

getopt is a command-line parameter processing tool in the GNU toolset. It supports more options and syntax, can handle short options and long options, and can also handle continuous options. The syntax of getopt is more complicated than that of getopts. It needs to specify an option string, which contains all supported options and parameters. getopt saves the parsed options and parameters in an array, which needs to be processed in the code.

The getopt command has the following parameters:

  • -o: Specifies single-character options. No separator is required between options.
  • --long: Specifies the long option. Long options are separated by commas.
  • :: A colon is added after the option to indicate that the current option requires a parameter value.
  • --: Split options and parameters.
  • "$@": Indicates that all command line parameters are passed to the getopt command as a string.

options=$(getopt -o n:a:g:p --long name:,age:,gender:,print -- "$@") will parse command line options and parameters, And store the converted options and parameters in the variable options. This variable is usually passed to an eval command for processing, for example:

eval set -- "$options"
# test script
#!/bin/bash
# parse command line arguments
options=$(getopt -o n:a:g:p --long name:,age:,gender:,print -- "$@")
eval set -- "$options"

# Extract options and parameters
while 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 variable
if [ -z "$age" ]; then
    echo "Error: age is required"
    exit 1
the fi
if [ -z "$name" ]; then
    echo "Error: name is required"
    exit 1
the fi
if [ -z "$gender" ]; then
    echo "Error: gender is required"
    exit 1
the fi

# Judgment switch option
if [ "$print" = true ]; then
    echo "NameVal: $name; AgeVal: $age; GenderVal: $gender";
the fi
# script call (long option)
./script.sh --name Kite --age 18 --gender f -p
NameVal: Kite; AgeVal: 18; GenderVal: f
# script call (single character option)
./script.sh -n Kite -a 18 -g f -p
NameVal: Kite; AgeVal: 18; GenderVal: f

3. Summary

It is also very powerful if you can use shell scripts flexibly.