08 May 2021
Normally a bash script has some input parameters used to processing data and there are at least two ways to read them:
In this way you make explicit the parameter name with its value.
Example:
./print_phrase_by_name.sh --first-word "Hello" --second-word "World!"
Bash script:
#!/bin/bash
FIRST_WORD=""
SECOND_WORD=""
while [[ ${#} -gt 0 ]]; do
case "${1}" in
--first-word)
if [ ${#2} -ne 0 ]; then
FIRST_WORD="${2}"
shift 2
fi
;;
--second-word)
if [ ${#2} -ne 0 ]; then
SECOND_WORD="${2}"
shift 2
fi
;;
--help)
echo "usage: print_phrase_by_name.sh [--help] [--first-word <word>] [--second-word <word>]"
echo "OPTIONS"
echo " --first-word"
echo " First word to print."
echo ""
echo " --second-word"
echo " Second word to print."
echo ""
echo " --help"
echo " Read this manual."
exit 0
;;
*)
echo "Invalid options found ${1}, please read --help for more information."
exit 1
;;
esac
done
# TODO check FIRST_WORD and SECOND_WORD are not empty
echo "${FIRST_WORD} ${SECOND_WORD}"
exit 0
For me read by position is not the first choice because it obfuscated the meaning of the input parameter.
The advantage of this approach compared to by name is more concise.
Example:
./print_phrase_by_pos.sh "Hello" "World!"
Bash script:
#!/bin/bash
FIRST_WORD="${1}"
SECOND_WORD="${2}"
# TODO check FIRST_WORD and SECOND_WORD are not empty
echo "${FIRST_WORD} ${SECOND_WORD}"
exit 0
Copy previous example in /tmp/print_phrase_by_pos.sh
and /tmp/print_phrase_by_name.sh
Then give them execution permission (like chmod +x) for both scripts.
docker run -it --mount 'type=bind,source=/tmp/,target=/tmp/' -w /tmp ubuntu /bin/bash
From inside the container:
# ./print_phrase_by_name.sh --first-word "Hello" --second-word "World!"
Hello World!
# ./print_phrase_by_name.sh --help
usage: print_phrase_by_name.sh [--help] [--first-word <word>] [--second-word <word>]
OPTIONS
--first-word
First word to print.
--second-word
Second word to print.
--help
Read this manual.
# ./print_phrase_by_pos.sh "Hello" "World!"
Hello World!