【问题标题】:assign incomplete command to variable / bash将不完整的命令分配给变量/ bash
【发布时间】:2014-02-26 00:53:36
【问题描述】:

我被一个相当愚蠢的 bash 脚本困住了:

CMD="get database" /   #embedded,specific platform command
DATA="tree path Uo5 Uu7"

custom_command='grep -i Arte | awk -F '[:]' '{print $2}'

这就是我想做的:

VAR=`$CMD "show data $DATA" | $custom_command`   <--not working
VAR=`$CMD "show data $DATA" | grep -i Arte | awk -F '[:]' '{print $2}'` <--working

使用 $custom_command 会中断脚本。如何将 $custom_command 用于 VAR?

我使用 custom_command 来避免一遍又一遍地使用相同的字符串。你能帮忙吗?

【问题讨论】:

    标签: bash shell


    【解决方案1】:

    你可以这样做:

    custom_command="awk -F':' '/Arte/ {print \$2}'"
    var=$(eval "$CMD 'show data $DATA' | $custom_command")
    

    否则没有eval:

    custom_command="/Arte/ {print \$2}"
    var=$("$CMD" 'show data $DATA' | awk -F':' "$custom_command")
    
    • 您实际上并未向 grep 命令提供任何输入文件/数据
    • 但是这里实际上不需要 grep,因为 awk 也可以处理搜索部分

    【讨论】:

    • 谢谢,但实际上命令更大,只是发布了一个快捷方式。所以我真的需要在变量中包含自定义命令..这是个大问题。 (我会用你的方式,把它缩短 - 顺便说一句:))你认为我可以只使用自定义命令,然后添加一个
    • 我想要 $custom_command,而不是 $CMD ;) 管道不适用于此: grep: |: 没有这样的文件或目录 grep: awk: 没有这样的文件或目录 grep: '[=,] ': 没有这样的文件或目录 grep: '{print: 没有这样的文件或目录 grep: $2}'|: 没有这样的文件或目录 grep: 排序: 没有这样的文件或目录 grep: |: 没有这样的文件或目录 grep: grep: 没有这样的文件或目录 grep: [0-9]: 没有这样的文件或目录
    • 你可以随意命名你的变量,我的回答不会改变部分。我的答案只是为了修复你的 grep 并在 awk 本身中执行此操作。
    • 如果您在问题中发布脚本,我可以进行调查并提出建议。
    • 我编辑了我最初的问题以使其更清楚!我想用字符串变量替换 VAR 的第二部分!
    【解决方案2】:

    您需要进行评估。比如:

    FINAL_CMD="$CMD show data $DATA | $custom_command"
    VAR=$(eval $FINAL_CMD)
    

    或者为了更好地适应您的问题,请尝试:

    VAR=`$CMD "show data $DATA" | eval $custom_command`
    

    【讨论】:

      【解决方案3】:

      您不想将命令分配给bash 中的变量。你想写函数。

      custom_command() {
          grep -i Arte | awk -F '[:]' '{print $2}'   
      }
      

      【讨论】:

      猜你喜欢
      • 2021-06-11
      • 2012-07-16
      • 2011-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-25
      • 2011-01-19
      相关资源
      最近更新 更多