【问题标题】:How to split the variable or name into an variable?如何将变量或名称拆分为变量?
【发布时间】:2015-05-08 10:15:41
【问题描述】:

使用 shell 脚本,我想将名称拆分为一个变量。假设我的 .conf 文件中的数据是这样的:

ssh.user = root
ssh.server = localhost

然后我希望这个 ssh.user 在一个变量中,而 root 在另一个变量中?那我该怎么办?

【问题讨论】:

    标签: shell scripting


    【解决方案1】:

    如果您可以接受在变量名中不使用点的解决方案,您可以只使用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?

    【讨论】:

    • 在我的配置文件中数据是这样的。
    • 正如我在问题中提到的那样。那么如何在变量中分离这些数据请帮助我
    • @akshay 请参考我链接到的文章。我解释了采购,因为另一篇文章没有。
    • ,我希望 ssh.user 在一个变量中,然后将该变量用于进一步处理。
    • 那么如何将其用作变量呢? var1=ssh.user nad 然后 var1=root
    猜你喜欢
    • 2018-02-19
    • 2015-09-22
    • 2013-05-28
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-15
    • 2017-02-25
    相关资源
    最近更新 更多