bash/sh: special variables (exit code, pid, startup parameters, etc.)

Practice



In bash/sh, a number of special variables are available while scripts run. Let's take a look at them.


$1-$9

These are command-line parameters. That is, whatever the user entered separated by spaces after the script's name itself.

For example:
$ ./myscript.sh first second "third and more"

Here:
  • $1 will equal "first"
  • $2 will equal "second"
  • $3 will equal "third and more"


Since there can be more than 9 parameters, scripts can use the special shift directive. It shifts the entire set of variables left by one position.

For example, after issuing the shift command once, our variables from the example above will take on these values:
  • $1 will equal "second"
  • $2 will equal "third and more"
  • $3 - will be empty


$0

This variable holds the path and name of the script that the user ran.

Example 1:
$ ./myscript.sh
$0 = "./myscript.sh"


Example 2:
$ /usr/home/myscript.sh
$0 = "/home/user/myscript.sh"

As you can see, $0 doesn't necessarily contain the path to the script file at all.


$#

The number of parameters passed to the script from the command line.

Example:
$ ./myscript.sh param1 param2 param3
$# will equal 3


$?

The exit code (exit code, result code) with which the previous command finished. As a rule, an exit code of "0" means the command completed successfully, while anything other than zero indicates various errors, and the error codes are specific to the command being run.

Example:
#!/bin/sh

ping 192.168.0.5 -c 1 -n -W 1
res=$?

if [ "$res" -eq 0 ]; then
echo "Host 192.168.0.5 is reachable"
else
echo "Host 192.168.0.5 got lost somewhere"
fi


$$

PID - the process ID under which this script is running.

Example:
#!/bin/sh

pid=$$
echo $pid

This script will print the process ID under which the current script is running.


$!

The PID of the last process that was started in the background. For example, if you launch some process in the background, you might want to know its PID.

Example:
#!/bin/sh

./another_process &

apid=$!

echo $apid


$*

All the parameters passed from the command line, combined into a single string.

Example:
#!/bin/sh

echo $*

and now, running the following example, we get:
$ ./myscript.sh p1 p2 p3
p1 p2 p3

Comments

Admin 21-04-2020
спасибо за информацию, да "$@"эквивалентно "$1" "$2"...
Денис 21-04-2020
добавлю $@ - Все параметры, переданные из командной строки, в виде набора отдельных значений, можно перебирать в цикле:
for param in "$@"
do
echo $param
done

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "LINUX operating system"

Terms: LINUX operating system