Ana Sayfa / Linux / Bash Script / Internal variables

Internal variables

An overview of Bash’s internal variables, where, how, and when to use them.

Bash internal variables at a glance

Function/script positional parameters (arguments). Expand as follows
$* / $@$* and $@ are the same as $1 $2 … (note that it generally makes no sense to leave those unquoted)
“$*” is the same as “$1 $2 …” 1
“$@” is the same as “$1” “$2” …
Arguments are separated by the first character of $IFS, which does not have to be a space
$#Number of positional parameters passed to the script or function
$!Process ID of the last (righ-most for pipelines) command in the most recently job put into the background (note that it’s not necessarily the same as the job’s process group ID when job control is enabled)
$$ID of the process that executed bash
$?Exit status of the last command
$nPositional parameters, where n=1, 2, 3, …, 9
${n}Positional parameters (same as above), but n can be > 9
$0In scripts, path with which the script was invoked; with bash -c ‘printf “%s\n” “$0″‘ name args’: name (the first argument after the inline script), otherwise, the argv[0] that bash received.
$_Last field of the last command
$IFSInternal field separator
$PATHPATH environment variable used to look-up executables
$OLDPWDPrevious working directory
$PWDPresent working directory
$FUNCNAMEArray of function names in the execution call stack
$BASH_SOURCEArray containing source paths for elements in FUNCNAME array. Can be used to get the script path.
$BASH_ALIASESAssociative array containing all currently defined aliases
$BASH_REMATCHArray of matches from the last regex match
$BASH_VERSIONBash version string
$BASH_VERSINFOAn array of 6 elements with Bash version information
$BASHAbsolute path to the currently executing Bash shell itself (heuristically determined by bash based on argv[0] and the value of $PATH; may be wrong in corner cases)
$BASH_SUBSHELLBash subshell level
$UIDReal (not effective if different) User ID of the process running bash
$PS1Primary command line prompt; see Using the PS* Variables
$PS2Secondary command line prompt (used for additional input)
$PS3Tertiary command line prompt (used in select loop)
$PS4Quaternary command line prompt (used to append info with verbose output)
$RANDOMA pseudo random integer between 0 and 32767
$REPLYVariable used by read by default when no variable is specified. Also used by SELECT to return the user-supplied value
$PIPESTATUSArray variable that holds the exit status values of each command in the most recently executed
foreground pipeline.

Variable Assignment must have no space before and after. a=123 not a = 123. The latter (an equal sign surrounded by spaces) in isolation means run the command a with the arguments = and 123, though it is also seen in the string comparison operator (which syntactically is an argument to [ or [[ or whichever test you are using).


“$@” expands to all of the command line arguments as separate words. It is different from “$*”, which expands to all of the arguments as a single word.

“$@” is especially useful for looping through arguments and handling arguments with spaces.

Consider we are in a script that we invoked with two arguments, like so:

$ ./ "␣1␣2␣" "␣3␣␣4␣"

The variables $* or $@ will expand into $1␣$2, which in turn expand into 1␣2␣3␣4 so the loop below

for var in $*; do # same for var in $@; do
 echo \\<"$var"\\>

will print for both


While “$*” will be expanded into “$1␣$2” which will in turn expand into “␣1␣2␣␣␣3␣␣4␣” and so the loop:

for var in "$*"; do
 echo \\<"$var"\\> 

will only invoke echo once and will print


And finally “$@” will expand into “$1” “$2”, which will expand into “␣1␣2␣” “␣3␣␣4␣” and so the loop

for var in "$@"; do
 echo \\<"$var"\\>

will print


thereby preserving both the internal spacing in the arguments and the arguments separation. Note that the construction for var in “$@”; do … is so common and idiomatic that it is the default for a for loop and can be shortened to for var; do ….


To get the number of command line arguments or positional parameters – type:

echo "$#"

When run with three arguments the example above will result with the output:

~> $ ./ firstarg secondarg thirdarg


The maximum number of remembered commands:

~> $ echo $HISTSIZE


To get the name of the current function – type:

 echo "This function is $FUNCNAME" # This will output "This function is my_function"

This instruction will return nothing if you type it outside the function:

echo "This function is $FUNCNAME" # This will output "This function is"


The home directory of the user

~> $ echo $HOME


Contains the Internal Field Separator string that bash uses to split strings when looping etc. The default is the white space characters: \n (newline), \t (tab) and space. Changing this to something else allows you to split strings using different characters:

for field in ${INPUTSTR}; do
 echo $field

The output of the above is:



  • This is responsible for the phenomenon known as word splitting.


OLDPWD (OLDPrintWorkingDirectory) contains directory before the last cd command:

~> $ cd directory
directory> $ echo $OLDPWD


PWD (PrintWorkingDirectory) The current working directory you are in at the moment:

~> $ echo $PWD
~> $ cd directory
directory> $ echo $PWD

$1 $2 $3 etc..

Positional parameters passed to the script from either the command line or a function:

# $n is the n'th positional parameter
echo "$1"
echo "$2"
echo "$3"

The output of the above is:

~> $ ./ firstarg secondarg thirdarg

If number of positional argument is greater than nine, curly braces must be used.

# "set -- " sets positional parameters
set -- 1 2 3 4 5 6 7 8 nine ten eleven twelve
# the following line will output 10 not 1 as the value of $1 the digit 1
# will be concatenated with the following 0
echo $10 # outputs 1
echo ${10} # outputs ten
# to show this clearly:
set -- arg{1..12}
echo $10
echo ${10


Will return all of the positional parameters in a single string.

echo "$*"

Run the script with several arguments:

./ firstarg secondarg thirdar


firstarg secondarg thirdarg


The Process ID (pid) of the last job run in the background

~> $ ls &
testfile1 testfile2
[1]+ Done ls
~> $ echo $!


The exit status of the last executed function or command. Usually 0 will mean OK anything else will indicate a failure:

~> $ ls *.blah;echo $?
ls: cannot access *.blah: No such file or directory
~> $ ls;echo $?
testfile1 testfile2


The Process ID (pid) of the current process:

~> $ echo $$


Each time this parameter is referenced, a random integer between 0 and 32767 is generated. Assigning a value to this variable seeds the random number generator

~> $ echo $RANDOM
~> $ echo $RANDOM


Process ID (pid) of the current instance of Bash. This is not the same as the $$ variable, but it often gives the same result. This is new in Bash 4 and doesn’t work in Bash 3


An environment variable pointing to the Bash startup file which is read when a script is invoked.


An array containing the full version information split into elements, much more convenient than $BASH_VERSION if you’re just looking for the major version:

~> $ for ((i=0; i<=5; i++)); do echo "BASH_VERSINFO[$i] = ${BASH_VERSINFO[$i]}"; done
 BASH_VERSINFO[4] = release
 BASH_VERSINFO[5] = x86_64-redhat-linux-gnu


Shows the version of bash that is running, this allows you to decide whether you can use any advanced features:

~> $ echo $BASH_VERSION


The default editor that will be involked by any scripts or programs, usually vi or emacs.

~> $ echo $EDITOR


The hostname assigned to the system during startup.

~> $ echo $HOSTNAME


This variable identifies the hardware, it can be useful in determining which binaries to execute:

~> $ echo $HOSTTYPE


Similar to $HOSTTYPE above, this also includes information about the OS as well as hardware

~> $ echo $MACHTYPE


Returns information about the type of OS running on the machine, eg.

~> $ echo $OSTYPE


The search path for finding binaries for commands. Common examples include /usr/bin and /usr/local/bin.

When a user or script attempts to run a command, the paths in $PATH are searched in order to find a matching file with execute permission.

The directories in $PATH are separated by a : character.

~> $ echo "$PATH"

So, for example, given the above $PATH, if you type lss at the prompt, the shell will look for
/usr/kerberos/bin/lss, then /usr/local/bin/lss, then /bin/lss, then /usr/bin/lss, in this order, before concluding that there is no such command


The Process ID (pid) of the script or shell’s parent, meaning the process than invoked the current script or shell.

~> $ echo $$
~> $ echo $PPID


The number of seconds a script has been running. This can get quite large if shown in the shell:

~> $ echo $SECONDS


A readonly list of the options bash is supplied on startup to control its behaviour:

~> $ echo $SHELLOPTS


Outputs the last field from the last command executed, useful to get something to pass onwards to another command:

~> $ ls *.sh;echo $_

It gives the script path if used before any other commands:

echo "$_"


~> $ ./ # running

Note: This is not a foolproof way to get the script path


An array containing the numbers of groups the user is in:

#!/usr/bin/env bash
echo You are assigned to the following groups:
for group in ${GROUPS[@]}; do
 IFS=: read -r name dummy number members < <(getent group $group )
 printf "name: %-10s number: %-15s members: %s\n" "$name" "$number" "$members"


Outputs the line number in the current script. Mostly useful when debugging scripts.

# this is line 2
echo something # this is line 3
echo $LINENO # Will output 4


When the bash command is executed a new shell is opened. The $SHLVL environment variable holds the number of shell levels the current shell is running on top of.

In a new terminal window, executing the following command will produce different results based on the Linux distribution in use.

echo $SHLVL

Using Fedora 25, the output is “3”. This indicates, that when opening a new shell, an initial bash command executes and performs a task. The initial bash command executes a child process (another bash command) which, in turn, executes a final bash command to open the new shell. When the new shell opens, it is running as a child process of 2 other shell processes, hence the output of “3”.

In the following example (given the user is running Fedora 25), the output of $SHLVL in a new shell will be set to “3”. As each bash command is executed, $SHLVL increments by one.

~> $ echo $SHLVL
~> $ bash
~> $ echo $SHLVL
~> $ bash
~> $ echo $SHLVL

One can see that executing the ‘bash’ command (or executing a bash script) opens a new shell. In comparison, sourcing a script runs the code in the current shell.

#!/usr/bin/env bash
echo "Hello from My shell level is $SHLVL"
source ""

#!/usr/bin/env bash
echo "Hello from My shell level is $SHLVL"

#!/usr/bin/env bash
echo "Hello from My shell level is $SHLVL"


chmod +x && chmod +x


Hello from My shell level is 4
Hello from My shell level is 5
Hello from My shell level is 5


A read only variable that stores the users’ ID number:

~> $ echo $UID

Bunada Göz Atın

PHP Types

Type Comparison There are two types of comparison: loose comparison with == and strict comparison …

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir