Search code examples
bashvariablesargumentspromptdefault-value

Bash: Take argument or read -p prompt it


What's the most elegant way of: take supplied parameter or "read -p prompt" in case it's missing?

I can do some if--else

if [ -z "$1" ]; then
    read -p "supply x:" x
else
    x="$1"
fi

However, I wonder if I can combine it somehow with some shorter syntax like

x=${1:-foo}

Is there any more concise way than if--else ? Or it if--else the way to go?


Solution

  • I whole-heartedly advise against this as the correct behavior is to either provide a default or terminate with an error message, but if you insist on doing this monstrosity, you can use:

    x=${1-$(read -p prompt: v; echo "$v")}
    

    This only allows a single line of input the be used, but that is probably desirable behavior. With the caveat that the overall behavior is not desirable! This is a terrible thing to do!