Other Shell Features

Troubleshooting

Running your script

  • Remember you can run your script in one of two ways
    • Preface script with absolute or relative path
    • ../somescript.sh or /home/bob/bin/scrip.sh
    • Must make executable to do this
    • Preface with bash
    • bash somescript.sh
  • Make sure shebang is correct.

Running your script

  • myscript.sh results in command not found
    • You haven't given the full path OR
    • you haven't added your script path to the $PATH variable
      • Best place to modify $PATH is probably in ~/.bash_profile
  • What is the difference between:
    • ./myscript.sh AND
    • .myscript.sh

Running your script

  • Don't name your script the same name as any built-in commands
    • I.e. don't name it test

Quoting variables

    X=$Y $Z #is bad
    X="$Y $Z" is better
  • The first one would assign the contents of Y into X, then (since there is a space) would try to run whatever is in $Z.
  • It's generally a good idea to quote your assignments to a shell variable. That way you are assured of getting only one assignment and not encountering this problem.

Deleting files

Never do:

    rm -rf $files_to_delete

Never, ever, ever do:

    rm -rf /$files_to_delete

Use this instead:

    [ -n "$files_to_delete" ] && rm -rf $files_to_delete

Best practices

  • Initialize your variables, especially if they are numbers and you want to use them in printf statements.
  • Put quotes around your arguments if they could ever be null, and especially when used in printf statements.
  • Make sure you have the correct number of arguments, especially considering what the line will look like after the shell substitutions have occurred.
  • The safest way to display an arbitrary string is to use printf '%s\n' "$string".