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.

2
  • declare -rl HOSTNAME="$FQHN". See: help declare Commented Mar 12, 2018 at 6: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. Commented Mar 12, 2018 at 14:17

1 Answer 1

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%%.*}
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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 ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.