Input
Positional Parameters
Positional Parameters, script positional parameters.
$0
: script name, including path.$1
: the first argument, and so on.${10}
: arguments greater than 9 need to use curly braces.
BASENAME
Can remove the script’s path, leaving only the name.
Usage in the script.
Special Parameters
Shift Parameters
The shift
command can shift the positional parameters to the left by one position.
Script Options
Options are single letters preceded by a single hyphen, such as -a
. Since options and arguments are both located after the script, to distinguish them, a double hyphen --
is usually used, with options on the left and arguments on the right, for example.
To correctly interpret options and arguments in the script is not a trivial task, for which the official provides two tools.
getopt
- External command.
- Supports long options, such as
--help
. - Suitable for complex command-line tools.
getopts
- Internal command.
- Does not support long options.
- Suitable for simple option scenarios.
There are also many option interpretation projects on Github.
Getopt Command
optstring
: the definition of the options.parameters
: the content of the options.
For example, for optstring=ab:c
.
- Single letters
a
andc
represent options without values. - The letter
b
followed by:
indicates an option with a value.
Let’s look at the output of the following example.
It can be seen that it uses --
to separate options and arguments.
Getopts Command
getopts
is a built-in command in Bash, which will parse options one by one and store the information of the options in specific variables, making it convenient for scripts to access. This is the command for me, a small potato.
name
: the name of the current option.OPTIND
: each time an item is processed, this value will increase by 1.OPTARG
: if the option has a value, it will be saved in this variable.