我需要从输入中导出值。然而它在 bash 中失败了。
这是代码 -
echo "Please enter HOST :"
read RDSHOST && export RDSHOST
我的价值是这样的 - myserver.abc-zone5.com
当我运行脚本时出现此错误 - 寻找匹配的“”语法错误时出现意外的 EOF:意外的文件结尾
需要了解如何用双引号导出变量以避免此错误
答案1
echo "Please enter REGION to login :"
read region && export region
echo "Please enter HOST to login :"
read HOST && export HOST
echo "Please enter Port to login :"
read localport && export localport
echo "Please enter username to login : "
read username && export username sql "host=$HOST port=$localport user=$username --region=$region"
echo "username sql \"host=$HOST port=$localport user=$username --region=$region\""
输出:
Please enter REGION to login :
ASIA
Please enter HOST to login :
localhost
Please enter Port to login :
6000
Please enter username to login :
foo
username sql "host=localhost port=6000 user=foo --region=ASIA"
答案2
shas的答案很好,我想补充一点,export
在将值分配给变量后不必设置变量的属性。这意味着您可以在不干扰脚本主要流程的情况下进行导出:
# prep for user input
export region
export HOST
export localport
export username
# prompt user for input
echo 'Please enter REGION to login :'
read region
echo 'Please enter HOST to login :'
read HOST
echo 'Please enter Port to login :'
read localport
echo 'Please enter username to login :'
read username
# show and invoke the sql command
echo "sql \"host=$HOST port=$localport user=$username --region=$region\""
sql "host=$HOST port=$localport user=$username --region=$region"
此外,export
可以使用多个变量的名称来设置属性,从而使该部分代码更短:
# prep for user input
export region HOST localport username
# prompt user for input
echo 'Please enter REGION to login :'
read region
echo 'Please enter HOST to login :'
read HOST
echo 'Please enter Port to login :'
read localport
echo 'Please enter username to login :'
read username
# show and invoke the sql command
echo "sql \"host=$HOST port=$localport user=$username --region=$region\""
sql "host=$HOST port=$localport user=$username --region=$region"
(我还将提示字符串用单引号括起来,因为它们不会扩展任何变量,并在调用它之前回显 sql 命令,因此如果 sql 命令挂起,用户知道脚本正在做什么)