Variables

  • Everything in bash is strings

  • How to declare

    • var="value"

    • var=`result of instructions`

    • var=$(result of instructions)

  • Differences:

var="hi"
echo $var
 - hi
var2='hi'
echo $var2
 - hi
 
echo "hi $var" # access to value
 - hi hi
echo 'hi $var' # doesn't access to value
 - hi $var
 
variable=`pwd`
echo $variable
 - /root

# 2 ways same result

variable=`ls -la | wc-l`
echo $variable
 - 7
 
var=$(ls -la | wc-l)
echo $var
 - 7
  • Scope:

    • Global if declared in script

    • Local if declared inside a function

Data read by keyboard

Special variables

  • $? : shows outcome from last execution (gives 0 for true and enything else for false). Shows if last instruction were correctly ran or not.

  • $$ : PID from script's process

  • $1..$9 : first 9 parameters passed to script

    • $0: shows the name of the script

  • $@ : shows all the parameters passed to script

  • $# : shows the number of parameters passed to the script

  • $USER: user name who ran the script

  • $RANDOM: returns a random number everytime an 'echo' is done towards it

Env variables

  • env : shows the list of env variables (caps)

  • $SHELL : type of shell being used

  • $PATH : different directories where the commands are searched

  • $USERNAME : shows username

Last updated