#!/bin/sh help() { echo "nx - create new script" echo "USAGE: nx " } err() { printf '%s: %s\n' "$0" "$@" >&2; exit 1; } warn() { printf '%s: %s [Y/n] ' "$0" "$@" >&2; read -r arg case "$arg" in ''|y|Y) ;; *) exit ;; esac } while getopts 'h' o; do case "$o" in h) help >&2; exit ;; *) err "invalid option -- '$OPTARG'" ;; esac done shift $((OPTIND - 1)) [ "$#" -lt 1 ] && help && exit 1 [ "$#" -gt 1 ] && err "too many arguments. Only one expected" new_file() { cat << EOF > "$1" #!/bin/sh help() { echo "$1 - USAGE: $1 [OPTION]... OPTIONS: -h show this help message"; } err() { printf '$1: %s\n' "\$@" >&2; exit 1; } while getopts 'h' o; do case "\$o" in h) help; exit ;; *) err "invalid option -- '\$OPTARG'" ;; esac done shift \$((OPTIND - 1)) [ "\$#" -lt 1 ] && help >&2 && exit 1 EOF chmod u+x -- "$1" || exit } file="$1" if [ -f "$file" ]; then [ ! -w "$file" ] && chmod u+rw "$file" if [ -s "$file" ]; then warn "'$file' already exists, edit existing file?" || exit else warn "an empty file '$file' already exists, fill and edit?" && new_file "$file" fi elif [ -e "$file" ]; then err "'$file' already exists and is a non-regular file" else new_file "$file" fi ls -lF --color -- "$file" ${EDITOR} "$file"