Skip to content

Instantly share code, notes, and snippets.

@apolopena
Last active March 28, 2022 04:00
Show Gist options
  • Save apolopena/c13d1aadc8077e4df7aa7f83ffc84e63 to your computer and use it in GitHub Desktop.
Save apolopena/c13d1aadc8077e4df7aa7f83ffc84e63 to your computer and use it in GitHub Desktop.
A cheat sheet of useful shell and bash snippets. This is not a POSIX compliant cheat sheet.

Exit codes and doing nothing

You may find yourself needing to manipulate exit codes or how a script behaves with them.

Sometimes in shell programming doing nothing is very useful.

The null utility : always returns an exit code of 0

Use : to:

  • Force a command to never return an error such as when you want the output of an error but not the exit code that goes with it.
ssh user@${i} 'echo OK' || :;
  • Create a file without running a program which is much faster than using touch. Although for most shells > myfile works just fine.
: > /path/to/file
  • Leave a placeholder in a conditional for code you intend to write (not the best habit).
if validate_somthing; then :; else echo "validation error"; fi


The true command : always returns an exit code indicating success (for most shells this is 0), and the false command always returns an exit code indicating failure (for most shells this is 1).

Use true and false to:

  • Simulate a boolean value by conditionally writing a function, such as as when you need to know if your script was run from a terminal or not.
if [ -t 1 ]; then
  is_tty() {
    true
  }
else
  is_tty() {
    false
  }
fi
  • or be explicit and call true and false using the longhand /bin/true and /bin/false
if [ -t 1 ]; then
  is_tty() {
    /bin/true
  }
else
  is_tty() {
    /bin/false
  }
fi


The -e shell option is used to force orce a script to exit whenever a command exits with a non zero exit code.

Use -e:

  • with a shebang line
#!/bin/bash -e
  • invoked through the bash interpreter
bash -e myscript.sh
  • in a script using the set builtin
#!/usr/bin/bash
cd .. || echo "could not move up a directory"
set -e
echo "the next command will fail" && /bin/false
echo "this line will never run"

Use : and the shell option -e together such as when you want a grep command that found nothing to not kill your script.

set -e
grep mypattern myfile || :
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment