Variables

There are some rules about variable names:

  • Variable names may consist of alphanumeric characters (letters and numbers) and underscore characters.
  • The first character of a variable name must be either a letter or an underscore.
  • Spaces and punctuation symbols are not allowed.

global variables

  1. #!/bin/bash
  2. var1=1
  3. var2=2

local variables

  1. function func() {
  2. local foo
  3. foo=1
  4. }

constant variables

  1. FILENAME='~/.bashrc' # Just a common convention
  2. declare -r FILENAME='~/.bashrc' # -r: readonly
  3. declare -i FILENAME='~/.bashrc' # -i: integer

Parameter Expansion

$VARNAME
${VARNAME}

  1. dirname='~/dir/'
  2. echo "$dirname"
  3. filename=${dirname}filename
  4. # bad: filename=$dirnamefilename

declare

  1. #!/bin/bash
  2. declare -r readonlyVar
  3. declare -i integerVar
  4. declare -u upperVar
  5. declare -l lowerVar

Functions

  1. function name {
  2. commands
  3. return [EXIT_STATUS] # optional, default return 0, menas success
  4. }
  5. name {
  6. return [EXIT_STATUS]
  7. }
  8. name # call name
  9. echo $? # ? is exit code of name
  • Shell function names follow the same rules as variables.
  • A function must contain at least one command.
  • return [EXIT_STATUS]
    • Terminate the function with exit status of EXIT_STATUS
    • When no argument is passed, the exit status defaults to the exit status of the last command executed.
    • return command is optional, and the exit status defaults to the exit status of the last command executed.