bler
bler

Reputation: 125

How can I supress output of a function only if it succeded?

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

Answers (2)

konsolebox
konsolebox

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

tjm3772
tjm3772

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

Related Questions