Shell

  • Edit current line in Vim with C-x C-e.
  • Open last command in Vim with fg.
  • Print function definitions with declare -f myfunc
  • Also see Bash and Zsh
  • heredoc

Shell Builtins

Shell Options

# write trace to stderr for every command
set -xv
 
## Error Handling
set -o errexit;
set -o pipefail;
set -o nounset;

POSIX: Add values to input Arguments with set

#!/bin/sh
set -- one two
echo $1
echo $2
 
# also useful when looping
for arg; do
  echo $arg
done

Shell Loopings

# endless
while :; do
    echo "endless loop"
done
 
# for loop with counter
for (( i=1 ; i<=5 ; i++ )); do
  echo "Hello World"
done
 
# until loop
until obs-cli OpenProjector >/dev/null 2>&1; do
    log "waiting for obs to get ready ..."
    sleep 1
done;
 
# Columnized printing
for d in ./*; do
    printf "$(basename "$d")"
    printf " "
    echo " asdfasdf asd as df"
done | column -t
 
# iterator over results from find with while loop
# loops over found git repositories
find -L ~/repos -name .git -type d -prune -exec dirname {} \; |
    while read -r line; do
        echo line: $line
    done

Printing Color Codes

# print red text
echo -e "\e[31mRed Text\e[0m"
# or use tput
_RED=$(tput setaf 1)
_BLUE=$(tput setaf 4)
_GREEN=$(tput setaf 2)
_GOLD=$(tput setaf 3)
_BOLD=$(tput bold)
_RESET=$(tput sgr0)
printf "%s=%d\n" "$char" "'$char"

Test Color displaying in shell

  • printf '\e[%sm ' {30..37} 0; - print foreground
  • printf '\e[%sm ' {40..47} 0; - print background