Is it possible to do nested parameter expansion in bash? (e.g.: VAR=${{1:-$ENV_VAR}:-hard-coded default}
)
I want to set command line arguments with default values. However, before using a hard-coded default I would like to check for an environmental variable. Thus, the expected order would be (e.g.):
$1 -> $ENV_VAR -> "hard-coded default"
I can solve this problem in two ways (see below), but both look bad:
1:
VAR=${1:-$ENV_VAR}
VAR=${VAR:-hard-coded default}
2:
VAR2=$([ -n "${1:-$ENV_VAR}" ] && echo "${1:-$ENV_VAR}" || echo "hard-coded default")
Minimal example:
$ cat test.sh
#!/bin/bash
VAR=${1:-$ENV_VAR}
VAR=${VAR:-hard-coded default}
VAR2=$([ -n "${1:-$ENV_VAR}" ] && echo "${1:-$ENV_VAR}" || echo "hard-coded default")
echo ENV_VAR is "'$ENV_VAR'"
echo VAR is "'$VAR'"
echo VAR2 is "'$VAR2'"
$ ./test.sh
ENV_VAR is ''
VAR is 'hard-coded default'
VAR2 is 'hard-coded default'
$ env ENV_VAR=test ./test.sh
ENV_VAR is 'test'
VAR is 'test'
VAR2 is 'test'
$ ./test.sh parameter
ENV_VAR is ''
VAR is 'parameter'
VAR2 is 'parameter'
$ env ENV_VAR=test ./test.sh parameter
ENV_VAR is 'test'
VAR is 'parameter'
VAR2 is 'parameter'
VAR=${{1:-$ENV_VAR}:-hard-coded default}
) can be done. – Protozsh
could I guess – ReldVAR=${1:-${ENV_VAR:-hardcoded}}
– Compressedfc
), for the editor being used: "Ifename
is not given, the value of the following variable expansion is used:${FCEDIT:-${EDITOR:-vi}}
." – Numerator