Bash 字符串参数打印有不必要的撇号

时间:2021-01-06 13:58:29

标签: string bash docker

我正在 ubuntu 18 操作系统上编写 BASH 脚本。 我正在对字符串进行操作(追加、剪切) 之后,我想将它用作 docker 命令的参数。 问题是它以撇号返回,而我只需要不带撇号的值。

if [[ "${TESTIM_LABEL}" =~ "," ]]; then
    IFS=','
    read -a strarr <<< "$TESTIM_LABEL"
    LABELS=""
    prefix=" --label "
    for val in "${strarr[@]}";
    do
      LABELS+=${prefix}${val}
      echo "$LABELS"

    done
        printf "$LABELS"
  else
      printf "im outside the IF"
      LABELS="--label ${TESTIM_LABEL}"
fi

在此 IF 语句上,当条件为真且我在 IF 内时,打印 LABELS 变量的值没有撇号 但 当我稍后将此参数用作较长命令的一部分时,它会被插入带撇号

示例:

    RESULT=$(docker run --rm -e rpLaunch="${RP_LAUNCH_NAME}" -e rpTeam="${RP_TEAM}" -e rpUuid="${rp_uuid}" -e rpBranchNameTag="${BRANCH_NAME}" -e rpDescription="${RP_DESCRIPTION}" -v $2:/opt/testim-runner ${TESTIM_DOCKER} \
  --token ${TESTIM_TOKEN} \
  --project "${TESTIM_PROJECT}" \
  ${LABELS} 

输出将是(插入到 IF "xxx,yyy" 之后):

docker run --rm -e rpLaunch=master/testim/@arion_ab_testing -e rpTeam=SocialArion -e rpUuid= -e rpBranchNameTag=master -e rpDescription=http://jenkins-prod-search.internalk.com/job/ui-pull-request/3127/ -v /home/centos/jenkins/workspace/ui-pull-request:/opt/testim-runner testim/docker-cli --token Dt9kFOtOhNcMum2gZjvnapOpGyq8vgreEnZOJF2nR9SeCJaRGE --project bJFghGy6Jo9yvtOO3ZiO ' --label xxx --label yyy'

以及 ' --label xxx --label yyy' 周围的撇号需要删除。

我该怎么做?

2 个答案:

答案 0 :(得分:0)

[评论太长] ...我认为这可能归结为如何填充 TESTIM_LABEL 变量的(简单)问题。 [注意:OP 尚未向我们展示如何填充所述变量。]

一个简单的例子,使用 OP 的当前代码进行演示:

#!/usr/bin/bash

read -p "enter TESTIM_LABEL: " TESTIM_LABEL      # added to OP's code; have user enter value @ prompt;
                                                 # the rest is cut-n-pasted from the question ...

if [[ "${TESTIM_LABEL}" =~ "," ]]; then 
    IFS=','
    read -a strarr <<< "$TESTIM_LABEL"
    LABELS=""
    prefix=" --label "
    for val in "${strarr[@]}";
    do
      LABELS+=${prefix}${val}
      echo "$LABELS"

    done
        printf "$LABELS"
  else
      printf "im outside the IF"
      LABELS="--label ${TESTIM_LABEL}"
fi

几个示例在我们不(不)引用输入的地方运行:

$ testim.bash
enter TESTIM_LABEL: 'xxx,yyy'
 --label 'xxx
 --label 'xxx --label yyy'
 --label 'xxx --label yyy'              # unwanted quotes

$ testim.bash
enter TESTIM_LABEL: xxx,yyy
 --label xxx
 --label xxx --label yyy
 --label xxx --label yyy                # no quotes

当然,可能还有另一种解释,但如果 OP 提供有关如何设置 TESTIM_LABEL 变量的更多详细信息,将会有所帮助。

答案 1 :(得分:0)

像这样删除它们:

test="'test'"

#with
$ echo "$test"
'test'

#without
$ echo "${test//\'}"
test
相关问题