Variables
- Prefixed with "$" (when used as r-values)
Special variables
- $# : The number of command-line arguments
- $@ : The list of command-line arguments.
- $1..$9 : The first through ninth
positional parameters (arguments) (can access additional arguments by
enclosing the number in curly braces)
- $? : The return value of the most recently executed command.
Command-line arguments
shift
shift [n]
- Shifts the positional parameters by n (the default value of n is 1).
getopts
while getopts [letter[:]]+ <varname>; do
commands;
done
- Iterates through a loop once for each command-line option that matches one of the letters in the specified set of letters.
- Stores the matching letter in the specified variable.
- If the letter is specified with a colon following it, then the command-line option is expected to have an argument, separated from it by a blank space, which will be stored in the special variable OPTARG.
- Each time through the loop, the variable OPTIND is used to store the index of the next command-line argument to be processed.
- OPTIND is not automatically reset by the getopts command. Before using getopts again in the same shell invocation, the variable OPTIND must be manually reset.
# <script> -a -b apple -c
while getopts ab:c option; do
echo "Option: $option $OPTARG"
done
OPTIND="1" # Manually reset the $OPTIND variable
while getopts ab:c option; do
echo "Option: $option $OPTARG"
done
Script variables
<varname>=<value>
- By default, variables defined in a shell script are only available within that script.
greeting="hello"
name="Buford"
echo "$greeting $name"
Local variables
local <varname>[=<value>]
- Creates local variables for a function.
local dest="/usr/bin"
Commands
declare
declare [-xi] varname[=value]
- Declares a variable
- -x : Exports the variable for use by subshells (child scripts)
- -i : Treats the variable as an integer
export
export [-n] <varname>[=<value>]
- Allows child scripts to access a variable.
- A copy of the variable will be created for each new subshell generated (for each child script).
export source="/usr/local/bin"
export -n dest # Make the variable no longer be exported
readonly
readonly [varname]*
- Marks the variables as read-only
eval
eval [arguments]+
- Concatenates the arguments and runs them as a single command
- Arguments with blank spaces remain intact (they're not broken up
into multiple arguments)
Resources URL:
notes/bash/resources
Sources URL:
notes/bash/sources