# ~/.bash_functions # # Functions for commands that need arguments, conditionals, loops, # or more than simple text substitution. # ------------------------------------------------------------ # mkcd # ------------------------------------------------------------ # Create a directory and cd into it. # # Usage: # mkcd new/project/path mkcd() { if [ "$#" -ne 1 ]; then echo "Usage: mkcd DIRECTORY" >&2 return 2 fi mkdir -p -- "$1" && cd -- "$1" } # ------------------------------------------------------------ # extract # ------------------------------------------------------------ # Extract common archive types. # # Usage: # extract file.tar.gz # extract file.zip extract() { if [ "$#" -ne 1 ]; then echo "Usage: extract ARCHIVE" >&2 return 2 fi if [ ! -f "$1" ]; then echo "Not a file: $1" >&2 return 1 fi case "$1" in *.tar.bz2) tar xjf "$1" ;; *.tar.gz) tar xzf "$1" ;; *.tar.xz) tar xJf "$1" ;; *.tar) tar xf "$1" ;; *.tbz2) tar xjf "$1" ;; *.tgz) tar xzf "$1" ;; *.zip) unzip "$1" ;; *.gz) gunzip "$1" ;; *.bz2) bunzip2 "$1" ;; *.7z) 7z x "$1" ;; *.rar) unrar x "$1" ;; *) echo "Cannot extract: $1" >&2; return 1 ;; esac } # ------------------------------------------------------------ # backup # ------------------------------------------------------------ # Copy a file to file.bak.TIMESTAMP. # # Usage: # backup important.conf backup() { if [ "$#" -ne 1 ]; then echo "Usage: backup FILE" >&2 return 2 fi if [ ! -e "$1" ]; then echo "No such file: $1" >&2 return 1 fi cp -a -- "$1" "$1.bak.$(date +%Y%m%d-%H%M%S)" } # ------------------------------------------------------------ # croot # ------------------------------------------------------------ # cd to the root of the current Git repository. # # Usage: # croot croot() { local root root="$(git rev-parse --show-toplevel 2>/dev/null)" || { echo "Not inside a Git repository" >&2 return 1 } cd "$root" } # ------------------------------------------------------------ # serve # ------------------------------------------------------------ # Start a simple HTTP server in the current directory. # # Usage: # serve # serve 9000 serve() { local port="${1:-8000}" python3 -m http.server "$port" } # ------------------------------------------------------------ # psg # ------------------------------------------------------------ # Search running processes. # # Usage: # psg postgres psg() { if [ "$#" -eq 0 ]; then echo "Usage: psg PATTERN" >&2 return 2 fi ps aux | grep -i -- "$*" | grep -v grep } # ------------------------------------------------------------ # weather-resistant command checks # ------------------------------------------------------------ # Example helper for conditional integrations. # # Usage: # has git && echo "git is installed" has() { command -v "$1" >/dev/null 2>&1 }