Using shell scripting, I want to split the name into an variable. Suppose in my .conf file the data is like this:
使用shell脚本,我想将名称拆分为变量。假设我的.conf文件中的数据是这样的:
ssh.user = root
ssh.server = localhost
then I want this ssh.user in one variable and root in another variable? So what should I do?
那么我想在一个变量中使用ssh.user并在另一个变量中使用root?所以我该怎么做?
1 个解决方案
#1
If you can live with a solution that doesn't use dots in the variable names, you could just use source
(source will execute the file given as argument as a script):
如果你可以使用不在变量名中使用点的解决方案,你可以只使用source(source将执行作为参数作为脚本给出的文件):
A file called config
一个名为config的文件
sshuser = root
sshserver = localhost
`And then the script using that configuration:
`然后使用该配置的脚本:
#!/bin/bash
source config
echo $sshuser
will output
root
Several techniques other than sourcing are explained right here on * Reading a config file from a shell script
除了源之外的几种技术在*上解释了从shell脚本读取配置文件
Now, the fact that your variables contain a dot is an issue, but perhaps another technique (using awk
) explained in yet another SO question could help: How do I grab an INI value within a shell script?
现在,你的变量包含一个点的事实是一个问题,但也许另一个技术(使用awk)在另一个SO问题中解释可能有所帮助:我如何在shell脚本中获取INI值?
Applied to your case that will give something like
适用于你的情况会给出类似的东西
ssshuser=$(awk -F "=" '/ssh.user/ {print $2}' configurationfile)
Last potential issue, the whitespaces. See here How to trim whitespace from a Bash variable?
最后一个潜在的问题,即空白。请参见此处如何从Bash变量中修剪空格?
#1
If you can live with a solution that doesn't use dots in the variable names, you could just use source
(source will execute the file given as argument as a script):
如果你可以使用不在变量名中使用点的解决方案,你可以只使用source(source将执行作为参数作为脚本给出的文件):
A file called config
一个名为config的文件
sshuser = root
sshserver = localhost
`And then the script using that configuration:
`然后使用该配置的脚本:
#!/bin/bash
source config
echo $sshuser
will output
root
Several techniques other than sourcing are explained right here on * Reading a config file from a shell script
除了源之外的几种技术在*上解释了从shell脚本读取配置文件
Now, the fact that your variables contain a dot is an issue, but perhaps another technique (using awk
) explained in yet another SO question could help: How do I grab an INI value within a shell script?
现在,你的变量包含一个点的事实是一个问题,但也许另一个技术(使用awk)在另一个SO问题中解释可能有所帮助:我如何在shell脚本中获取INI值?
Applied to your case that will give something like
适用于你的情况会给出类似的东西
ssshuser=$(awk -F "=" '/ssh.user/ {print $2}' configurationfile)
Last potential issue, the whitespaces. See here How to trim whitespace from a Bash variable?
最后一个潜在的问题,即空白。请参见此处如何从Bash变量中修剪空格?