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

#!/bin/bash

echo "Insert a number from 0 t0 10"
read number

echo "The inserted is: $number" # will show the number
echo 'The inserted number is: $number' # will show $number instead of the value

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

#!/bin/bash

echo "Script name: $0"
echo "Value of parameter 1: $1"
echo "Value of parameter 2: $2"

echo "All parameters are: $@"

echo "Script with a total of $# parameters"

# ./parameters.sh argument1 argument2 argument4

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

#!/bin/bash

number=$1

echo $PATH | cut -f$number -d':' # -f is for field -d is delimiter

echo $PATH | awk -F: "{print $`echo $number`}" # alternative with awk instead of cut

Last updated