User-friendly Bash script template
Sometimes you need a user-friendly interface for scripts. Using raw ARG0, ARG1… is messy. Here’s a clean example of parsing arguments like -h or -a=one in Bash.
This script validates arguments, provides help output, and sets defaults for boolean and string options. It’s easy to extend for more flags.
script.sh
#!/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
Examples
[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|
Human Logic, AI Syntax...
Note on Content: I'm a Systems Engineer, not a native English writer. To ensure my technical ideas are clear and accessible, I use AI tools to polish the grammar and style. The workflow is simple: I provide the logic, the code, and the real-world experience. The AI handles the "English-to-Human" translation layer. If you find a bug, that's on me. If you find a perfectly placed comma, that's probably the AI.
Comments
Post a Comment