Skip to content

Instantly share code, notes, and snippets.

@mwinters0
Last active August 30, 2025 19:18
Show Gist options
  • Save mwinters0/b5496dee24d7e9bc0812dfee4951e0a1 to your computer and use it in GitHub Desktop.
Save mwinters0/b5496dee24d7e9bc0812dfee4951e0a1 to your computer and use it in GitHub Desktop.
my bash cheat sheet

Bash cheat sheet

Only the most common stuff

Script dir

# Doesn't work if "this file" is a symlink
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
# Doesn't work if you're trying to "source" this script
SCRIPT_DIR=$(dirname -- "$( readlink -f -- "$0"; )";)
# Works everywhere, but since this does `cd` out you may not be able to `cd` back in
pushd . > '/dev/null';
SCRIPT_PATH="${BASH_SOURCE[0]:-$0}";
while [ -h "$SCRIPT_PATH" ];
do
    cd "$( dirname -- "$SCRIPT_PATH"; )";
    SCRIPT_PATH="$( readlink -f -- "$SCRIPT_PATH"; )";
done
cd "$( dirname -- "$SCRIPT_PATH"; )" > '/dev/null';
SCRIPT_PATH="$( pwd; )";
popd  > '/dev/null';

Required / default vars

: ${REQVAR:?[You must set REQVAR]}
: ${MAYBEVAR:='default value'}

Pass all arguments

#!/bin/bash
otherprog "$@"   # equvalent to "$1" "$2" ...
otherprog $*     # same thing
otherprog "$*"   # equivalent to "$1 $2" 

All but the first:

#!/bin/bash
shift
otherprog "$@"   # equvalent to "$2" "$3" ...

Arrays

declare

my_arr=(foo bar baz)
my_arr+=(bing boom)    #append
arr_size=${#my_arr[@]} #count

iterate

# By value
for v in ${my_arr[@]}; do
    echo $v
done
# By index
for i in ${!my_arr[@]}; do
  echo ${my_arr[$i]}
done

delete matching (only first match)

# delete the 'foo' element from my_arr
my_arr=( "${my_arr[@]/foo}" )

or

delete='foo'
my_arr=( "${my_arr[@]/$delete}" )

Strings

trim whitespace

FOO=$(echo "$FOO" | xargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment