BASH: Special variables

Special variables are the most private shell variables. Special variables are made ​​read-only users (there are exceptions).

A few examples:

$0
name of the current script or a shell
$1.. $9
The parameters passed to the script (with the exception, the user can modify this type of special s $.)
$#
Contains a number of arguments passed on the command line.
$_
The path of what was called a script (shell)

Example:

# !/bin/bash

echo "I was salting out as: $_"


Effect of execution:

bash$ ./script.sh
Was invoked as. / script.sh

bash$ bash script.sh
Was invoked as /bin/bash

$@
This will show all the parameters passed to the script (or exception), equivalent to $1 $2 $3... if there are no parameters $@ expands to nothing.


Example:

# / bin / bash

echo "script started with parameters: $@"
Now, call this script with some parameters can be taken from the air such as:
. /file -a d


The effect will be as follows:

The script started with parameters -a d

$?

your last return code on the command line (0 if the command is finished successfully, another value if wrongly).


bash $ touch file
     bash $ cat file

After checking the value of the variable $? we obtain

bash $ echo $?
     0


Because the cat command is successful, the status variable contains the 0.

Now let's execute this command on non-existent file:

bash $ cat nonexistentfile.txt
     bash $ echo $?
     1


A value of 1 indicates that the above command has failed.

$$

PID of current shell process