简体   繁体   English

从文件中调用变量

[英]Call variables from a file

I need to retrieve variables that have been stored in a file. 我需要检索已存储在文件中的变量。 I am capturing the variable for an install of prostgress and some other programs. 我正在捕获用于prostgress和其他一些程序安装的变量。 Here is the script that I am using to create the variables.sh file at the beginning of the install script. 这是我用来在安装脚本的开头创建variables.sh文件的脚本。

#!/bin/bash # init #!/ bin / bash#初始化

function pause(){ read -p "$*" } 函数pause(){读取-p“ $ *”}

echo " Enter db user name " echo " " echo“输入数据库用户名” echo“”

read dbuser

echo " "
echo " Enter name of database  "
echo " "

read dbname

echo " "
echo " Enter db password "
echo "  "

read pws

echo " "
echo " Enter Port Number "
echo " "

read port

echo " "
echo " Enter URL i.e. my.hospital.com:8191 or 78.12.156.234:8191 "
echo " "

read url

cat > variables.dat << EOF

dbuser=$dbuser
dbname=$dbname
pws=$pws
port=$port
url=$url

EOF

if [ -f variables.sh ];

   then 
     echo " Data stored ready for next phase "

   else 

     echo " Data not stored - exit program start again "
     echo " "
     pause " Press [CTL] [Z] to exit the program now "

fi

chmod +x variables.sh

exit

During the execution of the other modules that I have written. 在执行我编写的其他模块期间。 I want to be able to open or call the variables file and pass variables to the executing script. 我希望能够打开或调用变量文件,并将变量传递给执行脚本。 So my pac-install.sh will include the variables.sh file and pass it's contents to the pac-install.sh script and be able to use the dbuser=$dbuser. 因此,我的pac-install.sh将包含variables.sh文件,并将其内容传递给pac-install.sh脚本,并能够使用dbuser = $ dbuser。 I hope this is more concrete. 我希望这更加具体。

Thanks for any help. 谢谢你的帮助。

Perhaps the bash source command is what you are looking for? 也许bash source命令就是您要找的东西?

If the file variables.sh contains the lines 如果文件variables.sh包含以下行

dbuser="the user"
dbname="the name"
...

then you can execute 然后你可以执行

source variables.sh

from a bash shell script to read and execute the commands from this file. 从bash shell脚本中读取并执行此文件中的命令。 This will assign the values to the shell variables $dbuser , $dbname etc. 这会将值分配给外壳变量$dbuser$dbname等。

Note that you should enclose the values in quotation marks if they contain spaces. 请注意,如果值包含空格,则应将其用引号引起来。

Example how to read back the variables from the file: 示例如何从文件中读取变量:

#!/bin/bash

source variables.sh
echo "dbuser=$dbuser"
echo "dbname=$dbname"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM