Just for fun I'd write:
Code: Select all
#!/bin/bash
set -u
function test() {
local -- type=''
local -- rc=0
while [[ -z "${type}" ]]; do
read -rp 'Testing your typing [y|other]: ' type
done
# rhs can be a string (quotes), glob pattern (no quotes), or a regular expression (=~)
if [[ "${type}" == 'y' ]]; then
printf -- 'You typed the word: %s\n' "${type}"
else
printf -- 'You typed some other word: %s\n' "${type}"
rc=1
fi
return "${rc}"
}
test && printf -- 'Return: %d\n' "${?}" || exit
There is some debate, if you have a literal string, that single quotes are "faster", because bash doesn't have to parse them.
This should work with single brackets too, but I prefer double. I like to define variables (local or declare), and also use set -u. A lot of times, set -x helps with debugging, especially with the single brackets. You can see what happens with the expansion. 99% of the time, quote expansions.
This is a helpful resource -
Unofficial Bash FAQ. Even if you know certain things, it'll show you alternatives or best practices in some cases.
In the above example, you'll notice $type is local. You could just declare it global, or you could do something with redirection like:
# within the function
...
printf -- 'You typed the word: %s\n' "${type}" >&3
printf -- '%s' "${type}"
...
# main: use command substitution & capture the value
exec 3>&1
type="$(test)"
exec 3>&-
Redirection is really powerful. I always have to think about it for awhile