sttemp (1486B)
1 #!/usr/bin/env sh 2 3 set -eu 4 5 ask () { 6 echo "Enter $1:" >&2 7 read -r value 8 echo "$value" 9 } 10 11 fill_vars () { 12 vars=$(envsubst -v "$(cat "$TEMPL")") 13 14 for var in $vars 15 do 16 [ -z "$(printenv "$var")" ] && 17 value="$(ask "$var")" && 18 eval "export $var=\"$value\"" 19 done 20 } 21 22 print_templ () { 23 envsubst <"$TEMPL" 24 } 25 26 print_help () { 27 cat <<EOF 28 sttemp - simple template manager 29 Usage: 30 -h Print this help 31 -l Print list of all templates 32 -v name Print all variables from template 33 -d dir Set directory with templates. 34 name Fill shell-like variables in template file and print his content. Missing environment variable will be asked on stderr. 35 EOF 36 exit 37 } 38 39 [ "$#" -lt 1 ] && print_help 40 41 while [ "$#" -gt 0 ]; do 42 case "$1" in 43 -h) 44 HELP=YES 45 shift 46 ;; 47 -l) 48 LIST_TEMPL=YES 49 shift 50 ;; 51 -v) 52 PRINT_VAR=YES 53 shift 54 ;; 55 -d) 56 TEMPL_DIR="$2" 57 shift 2 58 ;; 59 *) 60 TEMPL_NAME="$1" 61 shift 62 ;; 63 esac 64 done 65 66 [ -n "${HELP:-}" ] && print_help 67 68 [ -z "${TEMPL_DIR:-}" ] && 69 TEMPL_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/sttemp" && 70 mkdir -p "$TEMPL_DIR" 71 72 [ -n "${LIST_TEMPL:-}" ] && 73 ls "$TEMPL_DIR" && 74 exit 75 76 [ -z "${TEMPL_NAME:-}" ] && 77 echo "You should specify template name" && 78 exit 1 79 80 TEMPL="$TEMPL_DIR/$TEMPL_NAME" 81 82 [ ! -f "$TEMPL" ] && 83 echo "Template $TEMPL_NAME doesn't exist in $TEMPL_DIR" >&2 && 84 exit 1 85 86 [ -n "${PRINT_VAR:-}" ] && 87 envsubst -v "$(cat "$TEMPL")" && 88 exit 89 90 [ -n "${STTEMP_ASK:-}" ] && eval "$STTEMP_ASK" 91 fill_vars 92 print_templ