【发布时间】:2015-05-08 10:15:41
【问题描述】:
使用 shell 脚本,我想将名称拆分为一个变量。假设我的 .conf 文件中的数据是这样的:
ssh.user = root
ssh.server = localhost
然后我希望这个 ssh.user 在一个变量中,而 root 在另一个变量中?那我该怎么办?
【问题讨论】:
使用 shell 脚本,我想将名称拆分为一个变量。假设我的 .conf 文件中的数据是这样的:
ssh.user = root
ssh.server = localhost
然后我希望这个 ssh.user 在一个变量中,而 root 在另一个变量中?那我该怎么办?
【问题讨论】:
如果您可以接受在变量名中不使用点的解决方案,您可以只使用source(源将执行作为脚本作为参数给出的文件):
一个名为config的文件
sshuser = root
sshserver = localhost
`然后是使用该配置的脚本:
#!/bin/bash
source config
echo $sshuser
会输出
root
StackOverflow Reading a config file from a shell script 上解释了除采购之外的几种技术
现在,您的变量包含一个点这一事实是一个问题,但在另一个 SO 问题中解释的另一种技术(使用 awk)可能会有所帮助:How do I grab an INI value within a shell script?
应用于您的案例,会给出类似的结果
ssshuser=$(awk -F "=" '/ssh.user/ {print $2}' configurationfile)
最后一个潜在问题,空格。看这里How to trim whitespace from a Bash variable?
【讨论】: