Bash script template
Times to time I need to create script with user friendly interface, for this usage with ARG0, ARG1... bad form. Here example how to use normal argument's like "script.sh -h"
And how it's looks
#!/bin/bash -e for i in "$@" do case $i in -h|--help) cat <<'EOF' -a --a-arg - arg A '^[a-z]+$' EOF exit 1 shift ;; -a=*|--a-arg=*) CMD_arg="${i#*=}" shift ;; -b|--bool) CMD_bool=True shift ;; *) ;; esac done if [[ ! ${CMD_bool} ]]; then var_bool=False else var_bool=${CMD_bool} fi if [[ ${CMD_arg} =~ ^[a-z]+$ ]]; then var_arg=${CMD_arg} else echo "Wrong '-a' use '^[a-z]+$'" echo "Use -h|--help for help" exit 1 fi echo "-a |${var_arg}|" echo "-b |${var_bool}|" exit 0
And how it's looks
[root@b398b ~]# ./bash.sh -h -a --a-arg - arg A '^[a-z]+$'
[root@b398b ~]# ./bash.sh -a Wrong '-a' use '^[a-z]+$' Use -h|--help for help
[root@b398b ~]# ./bash.sh -a=one -a |one| -b |False|
[root@b398b ~]# ./bash.sh -a=1 Wrong '-a' use '^[a-z]+$' Use -h|--help for help
[root@b398b ~]# ./bash.sh -a=one -b -a |one| -b |True|
Comments
Post a Comment