Different variables & their usage in Shell-scripting

Different variables and their usage in Shell-scripting, explained in simple terms:

  • Local variables:

Variables declared using local are only accessible within the current function or script.

#!/bin/bash

function my_function {
    local my_var="hello"
    echo $my_var
}

my_function
echo $my_var # This will not print anything
  • Environment variables:

Variables set in the shell environment are available to all processes running in that shell.

#!/bin/bash

echo $HOME
echo $PATH
echo $PWD
  • Positional parameters:

Positional parameters are variables that contain the arguments passed to a script or function.

They are accessed using the $1, $2, $3, and so on, syntax.

$0 contains the name of the script itself.

#!/bin/bash

echo "The first argument is: $1"
echo "The second argument is: $2"
echo "The third argument is: $3"
  • Special variables:

Variables with predefined meanings in Bash.

Examples include

$? which contains the exit status of the last command,

$$ which contains the process ID of the current shell, and

$! which contains the process ID of the last command executed in the background.

#!/bin/bash

echo "The exit status of the last command was: $?"
echo "The process ID of the current shell is: $$"
echo "The process ID of the last command executed in the background was: $!"
  • User-defined variables:

Variables created in a script or function to store values.

#!/bin/bash

my_var="hello"
echo $my_var
  • Readonly variables:

Variables whose values cannot be changed after they are set.

They are typically used for values that should not be changed, such as configuration settings or constants.

#!/bin/bash

readonly PI=3.14159
echo "The value of PI is: $PI"
PI=3.14 # This will produce an error

Remembering these different areas of variables and their usage will help you write Bash scripts that are more flexible, modular, and easier to maintain.