IT 3110 : Advanced System Administration

Variables

Variables

Remember, they are containers that hold strings and numbers.

    a=3
    name=tom

Though, traditionally vars are written in ALL CAPS.

Variables

  • Remember, no spaces around the equal sign

  • Otherwise the shell would think the lhs is a command

  • Refer to a var with a $ in front of it:

     echo $a
    
  • Just remember that since everything in bash is a string, we need the dollar sign to indicate a variable reference

Scripting

  • Comments start with #
  • indenting using four spaces per level, with no tabs and especially no mixed tabs and spaces
  • Use meaningful names for variables and functions, and spell them out

Variables

Use the full syntax for a variable reference, which includes not just the dollar sign, but also braces around the variable name:

    somescript /tmp/rep${FN}port.txt

Export Variables

Export variables that you want to pass on to other scripts:

  • export SOMEVAR #basically make it a env var

     #var.sh
     #!/bin/bash
     
     myvar="IT3110"
     export myvar
     
     ./myscript.sh
     
     #somescript.sh
     #!/bin/bash
     
     echo "my var is ${myvar}"
     exit 0
    

Environment Variables & Shell vars

  • env shows all exported variables. (Environment variables)
  • set shows all shell variables (only available to current shell)

Try:

    foovar=3
    env | grep foovar; set grep foovar
    export foovar
    env | grep foovar; set grep foovar

Using parameters in a shell script

  • All strings present after the command invocation will be stored as numeric variables within the script.

     ./somecmd i like peaches
    
     #somecmd
     echo ${1}
    
     prints an 'i'
    
  • What would you change the script to, to print out 'peaches'?

  • You can use a $* to refer to all command line arguments.

  • You can use a $@ to be more robust (see 5.10 in book for more info)

Variables

Default values:

  • Use the `${:-} syntax
    • foo=${1:-something} #gets first command line argument if there, otherwise "something"

Variable Examples

    a=3
    name='tom'
    user=$(cat /etc/passwd | grep 1000 | awk '{ print $1}')
    mydate=$(date)