Skip to content
Snippets·Free

Bash snippets

20 Bash snippets for scripts: a safe header, argument checks, getopts, loops over files and arrays, cleanup with trap, retries and a few git commands. Type the prefix in a .sh file.

Free to install.

If PocketCode is installed on your Android device, this opens the page in the app.

Preview

5 of 20

Safe script headerstrict

Shebang plus set -euo pipefail so errors stop the script

#!/usr/bin/env bash
set -euo pipefail

$0

Check a command existshascmd

Stop with a message when a required program is missing

if ! command -v ${1:git} >/dev/null 2>&1; then
  echo "${1:git} is not installed" >&2
  exit 1
fi

Git: new branch from maingnewbr

Update main and create a branch from it

git switch ${1:main}
git pull --ff-only
git switch -c ${2:feature/name}

Git: undo the last commitgundo

Remove the last commit and keep its changes staged

git reset --soft HEAD~${1:1}

Replace text in many filessedall

Find files that contain a string and replace it in place (GNU sed)

grep -rl "${1:old}" ${2:.} | xargs sed -i "s/${1:old}/${3:new}/g"

Changes in 1.0.0

First version.

Related