【问题标题】:bash script: result of nested commands result not assigning to variablebash脚本:嵌套命令的结果未分配给变量
【发布时间】:2020-08-26 06:59:25
【问题描述】:

具有模式字符串:st2-api-alpha

想像 st2-api 一样修剪它们

基本上是想删除每个字符串第二次出现在“-”上的文本。

以下是我的陈述:

    for (( i=1; i<${#all_containers_list[@]}; i++ )){
        echo "trimmed[$i] - "${all_containers_list[i]}|cut -f1-3 -d'-'
        temp="$(${all_containers_list[i]}| cut -f1-3 -d'-')"
        echo "temp is:$temp"

        all_containers_list[i]=$temp
        echo "all_containers_list[$i] is ${all_containers_list[i]}"
    }

当我回显时:

修剪[1] - st2-ui

/home/****/st2-monitoring/monitors/getAllContainerStatus_v1.1.sh:行 139: st2-ui-server-alpha: 找不到命令

温度是:

all_containers_list[1] 是

修剪[2] - st2-api

/home/****/st2-monitoring/monitors/getAllContainerStatus_v1.1.sh:行 139: st2-api-alpha: 找不到命令

温度是:

all_containers_list[2] 是

修剪[3] - st2-whiteboard

/home/****/st2-monitoring/monitors/getAllContainerStatus_v1.1.sh:行 139: st2-whiteboard-alpha: 找不到命令

温度是:

all_containers_list[3] 是

修剪[4] - st2-aspose

/home/****/st2-monitoring/monitors/getAllContainerStatus_v1.1.sh:行 139: st2-aspose-alpha: 找不到命令

温度是:

all_containers_list[4] 是

修剪[5] - 确定的_bassi

/home/****/st2-monitoring/monitors/getAllContainerStatus_v1.1.sh:行 139:determined_bassi:找不到命令

温度是:

all_containers_list[5] 是

修剪[6] - st2-ui

/home//st2-monitoring/monitors/getAllContainerStatus_v1.1.sh:行 139:st2-ui--alpha:找不到命令

温度是:

all_containers_list[6] 是

  1. echo "trimmed[$i] - "${all_containers_list[i]}|cut -f1-3 -d'-' --- 这工作正常。

  2. 但是下面的任务不起作用 temp=$(${all_containers_list[i]}| cut -f1-3 -d'-')

请求您的帮助来解决这个问题! 操作系统为 CentOS , bash 脚本

【问题讨论】:

  • 下面也不工作 temp=echo ${all_containers_list[i]} | cut -f1-3 -d'-'
  • 试试temp=$(echo ${all_containers_list[i]}| cut -f1-3 -d'-')
  • 嗨@seumasmac 谢谢你的回复!这一次,错误消失了,但结果不是修剪后的值!以下是最新的日志 trimmed[1] - st2-whiteboard temp is:st2-whiteboard-alpha all_containers_list[1] is st2-whiteboard-alpha trimmed[2] - st2-ui .. .. trimmed[6] - st2- ui temp is:st2-ui-**** all_containers_list[6] is st2-ui-****
  • 为什么是cut -f1-3 -d'-'?不应该是cut -f1-2 -d'-'吗?
  • @M.NejatAydin -f1-3 只提供所需的输出,如 st2-api,但现在主要 pblm 是,结果没有分配给变量

标签: linux bash shell centos7


【解决方案1】:

我认为调用子进程只是为了删除字符串的一部分,有点矫枉过正。假设您已将字符串存储在变量中,例如

str=st2-api-alpha

你可以简单地做一个

if [[ $str =~ [^-]*-[^-]* ]]
then
  str=${BASH_REMATCH[0]}
fi

如果字符串不包含破折号,则保持不变。您可以将此解决方案简单地推广到您拥有字符串数组的情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-23
    • 2020-04-22
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2021-06-11
    • 2014-03-04
    • 2014-02-04
    相关资源
    最近更新 更多