1
#!/usr/bin/env bash

readonly FQHN=${1:-`hostname -f`}
readonly HOSTNAME=${FQHN%%.*}

I am struggling with the syntax to assign FQHN to the lower case of either the first command line argument or the output of hostname -f in a single assignment.

I have tried to use the various ways to lower case a variable reference contents as given in this answer but have not been able to integrate them into my code without having to use something like "${HOSTNAME,,}" or "${FQHN,,}" for every reference since you can not nest string substitutions.

I am really looking or a solution that does not rely on mutability.

  • `declare -rl HOSTNAME="$FQHN"`. See: `help declare` – Cyrus Mar 12 '18 at 06:13
  • @Cyrus - I like this as well, can you add it as an answer so it can get upvoted? All the years I have used `bash` and I have never come across a mention of the `declare` builtin. –  Mar 12 '18 at 14:17

1 Answers1

1

without having to use something like "${HOSTNAME,,}" or "${FQHN,,}" for every reference

Just do it once and assign the result back to the variable:

FQHN=${1:-`hostname -f`}
readonly FQHN=${FQHN,,}
HOSTNAME=${FQHN%%.*}

I don't know why you want to do it in a single line, but you can join them with ; or &&:

FQHN=${1:-`hostname -f`}; readonly FQHN=${FQHN,,}
HOSTNAME=${FQHN%%.*}

Or if you want to do it in a single assignment, you can do it the slow and verbose way:

readonly FQHN=$(tr '[:upper:]' '[:lower:]' <<< "${1:-`hostname -f`}")
HOSTNAME=${FQHN%%.*}
that other guy
  • 116,971
  • 11
  • 170
  • 194
  • If you want the end result to be `readonly`, simply do that when you have the final value. Use a temporary variable (you can make that `readonly`, too!) if you want to be strict about only assigning a value once; but there really is no way to make it more compact than this. – tripleee Mar 12 '18 at 04:47
  • *slow and verbose* is not a problem if it is also *clear and obvious*, not that anything in `bash` is *clear or obvious* unless you already know what you are doing ... –  Apr 16 '18 at 16:42