Set shell options in a script or at a global level.

Prevent accidental file overwrites

Copy and move

source

alias cp='cp -i'
alias mv='mv -i'

Redirection

Prevent output redirection using ‘>’, ‘>&’, and ‘<>’ from overwriting existing files. source

set -C

Similar to the above. source

set -o noclobber

When this is on, > file gives an error but >| file seems to force but need to confirm.

Exit on error

  • Using set docs.
      set -e
    
      # Reverse it with this:
      set +e
    
  • In a shebang. Only works with #!/bin/bash and not #!/usr/bin/env bash.
      #!/bin/bash -e
    
      echo 'Hello!'
    
  • Setting the body of the script.
      #!/usr/bin/env bash
    
      set -e
      echo 'Hello!'
    

Verbose

Print a trace of commands before running.

set -x

Or

$ bash -x my_script.sh