如果输入为空,bash读取的默认值


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}

给定上面的代码,我如何允许脚本用户按ENTER键以获得脚本上存在的预配置路径?在本例中应该是/home/somepath/script.py

上面的那个不起作用。它给了我一个read: 'directory=~/somepath/script.py': not a valid identifier错误。

提前感谢!

让它成为一个单独的步骤。

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 -

(将$USER变量分解为一个参数,而不是将其嵌入printf的格式说明符中…)

:(true的同义词)基本上是不会抛出错误的无操作,但是解析器仍然计算其参数。如果没有值,:=而不是:-会执行赋值,所以它设置了一个默认值。:)

或者,您可以在任何其他语句中使用默认赋值,例如日志输出。

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

实现同样的目的。