Reputation: 125
I have a function get_value
that either does an echo "$value"
or exits with an error message. I have a few other functions where I need to validate that the key exits. For that, I could just call get_value
, but in case that the key exists, I don't want it to display the echo
. How can I achieve that?
die() {
echo -e "$@" >&2
exit 1
}
get_value() {
local key="$1"
local value=
value=$(awk ...)
[ -z "$value" ] && die "Key '$key' doesn't exist."
echo "$value"
}
remove_key() {
local key="$1"
validate_key_exists "$key"
...
}
validate_key_exists() {
local key="$1"
# Call get_value "key". If the key exists, then don't display `echo "$value"`,
# otherwise `die`.
}
Upvotes: 1
Views: 43
Reputation: 75458
Don't use command substitution techniques when returning values.
get_value() {
local key="$1"
__=$(awk ...)
[[ $__ ]] || die "Key '$key' doesn't exist."
}
...
validate_key_exists() {
local key="$1" value
get_value key
value=$__
}
Upvotes: 0
Reputation: 3144
You can dump stdout from the function call to /dev/null.
validate_key_exists() {
local key="$1"
get_value "$key" >/dev/null
}
Upvotes: 1