BakedLizard
BakedLizard

Reputation: 33

Default value for bash read if input is null

VOL="~/somepath/script.py"
    printf "Drag and drop the '/somepath/vol.py' file on terminal./nPress enter for [/home/$USER/somepath/script.py]"
    read directory=${directory:-$VOL}

Given the code above, how can I allow the script user press the ENTER key for a preconfigured path present on the script? In this case it should be /home/somepath/script.py

The one above doesn't work. It gives me a read: 'directory=~/somepath/script.py': not a valid identifier error.

Many thanks in advance!

Upvotes: 0

Views: 1478

Answers (1)

Paul Hodges
Paul Hodges

Reputation: 15273

Make it a separate step.

VOL="~/somepath/script.py"
printf "Drag and drop the '/somepath/vol.py' file on terminal.
  Press enter for [/home/%s/somepath/script.py]" "$USER"
read directory
: ${directory:=$VOL} # = rather than -

(Factor the $USER variable out to an argument rather than embedding it in the printf's format specifier...)

: (synonym for true) is basically a no-op that won't throw an error, but the parser still evaluates its arguments. := instead of :- does an assignment if there's no value, so it sets a default. :)

Or, you could use the defaulting assignment in any other statement, like logging output.

echo "Using '${directory:=$VOL}'"

This accomplishes the same thing.

Upvotes: 1

Related Questions