Skip to content

Instantly share code, notes, and snippets.

@guoqiao
Last active August 24, 2025 22:52
Show Gist options
  • Select an option

  • Save guoqiao/88464033ee1f3d242d3ee3f6c26f29da to your computer and use it in GitHub Desktop.

Select an option

Save guoqiao/88464033ee1f3d242d3ee3f6c26f29da to your computer and use it in GitHub Desktop.
Shell Script Cheatsheet

How to source and export .env file

# an example .env file, which has no export keyword
$ cat .env
FOO=BAR123

# an example script uses $FOO
$ cat echo.sh
echo $FOO

# source and export .env file here
# yes, -a means enable, +a means disable here
$ set -a;source .env;set +a

# try to access the $FOO var in another script, to show it's exported
$ bash echo.sh
BAR123

Use C-like for loop with var name directly

N=3
# NOTE: you can use N directly here, instead of $N, although $N will also work
for ((i=0; i<N; i++));do
    echo "$i/$N: Hello, Shell!"
done

loop on string list

# loop on keywords without spaces
items="apple orange pear"
for item in $items; do
    echo $item
done

# if there are spaces, bash array is needed
things=("one word" "two words" "three words")
for item in "${things[@]}"; do
    echo "$item"
done

Use heredoc to build multi-line/complex string

PROMPT=${1:-"Fantasy dragon statue with wings"}
STYLE=${2:-"standard"}
JSON_DATA=$(cat << EOF
{
    "prompt": "${PROMPT}",
    "style": "${STYLE}"
}
EOF
)

curl -X POST -d "${JSON_DATA}" https://myapi.com/

slugify string with sed in shell

slugify() {
    echo "$1" | sed 's/ /-/g' | sed 's/[^a-zA-Z0-9-]//g' | sed 's/--*/-/g' | sed 's/^-\|-$//g'
}

# you could ajust sed patterns to meet your needs
$ slugify '\Fantasy #dragon @statue    with wings'
Fantasy-dragon-statue-with-wings
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment