shell 在Ansible中执行命令包含双引号

jw5wzhpr  于 2023-10-23  发布在  Shell
关注(0)|答案(1)|浏览(201)

我想执行以下包含双引号的命令:

- name: Initializing Kubernetes cluster
    shell: kubeadm init --control-plane-endpoint "hostname:port"

不知道它是否会工作或不,如果我检查命令如下:

- debug:
  msg: kubeadm init --control-plane-endpoint "hostname:port"

它给出kubeadm init --control-plane-endpoint \"hostname:port\"。为什么输出在引号之间包含额外的反斜杠?这个命令会正确执行吗?或者我必须添加一些东西,因为双引号?(我不能通过执行它来测试,因为它是一个生产服务器)

iibxawm4

iibxawm41#

Q:“为什么输出在引号之间包含额外的反斜杠?“**
答:Ansible在输出中转义了双引号,告诉你双引号是字符串的一部分。比如说,

- shell: echo "\"This is a double-quoted string.\""
      register: out

msg: |-
    .           123456789012345678901234567890123
    out.stdout: "This is a double-quoted string."
    length: 33
    out.cmd: echo "\"This is a double-quoted string.\""
  • 是否包含双引号取决于您。比如说,
- shell: echo "This is NOT a double-quoted string."
      register: out

msg: |-
    out.stdout: This is NOT a double-quoted string.
    out.cmd: echo "This is NOT a double-quoted string."

如果使用单引号样式,则不必转义双引号

- shell: echo '"This is a double-quoted string."'
      register: out

msg: |-
    .           123456789012345678901234567890123
    out.stdout: "This is a double-quoted string."
    length: 33
    out.cmd: echo '"This is a double-quoted string."'

用于测试的完整剧本示例

- hosts: localhost

  tasks:

    - shell: echo "This is NOT a double-quoted string."
      register: out
    - debug:
        msg: |
          out.stdout: {{ out.stdout }}
          out.cmd: {{ out.cmd }}

    - shell: echo "\"This is a double-quoted string.\""
      register: out
    - debug:
        msg: |
          .           123456789012345678901234567890123
          out.stdout: {{ out.stdout }}
          length: {{ out.stdout|length }}
          out.cmd: {{ out.cmd }}

    - shell: echo '"This is a double-quoted string."'
      register: out
    - debug:
        msg: |
          .           123456789012345678901234567890123
          out.stdout: {{ out.stdout }}
          length: {{ out.stdout|length }}
          out.cmd: {{ out.cmd }}

问:“由于双引号(一个字符串),我必须添加一些东西吗?“**
在下面的命令中,双引号将由shell解释

- shell: kubeadm init --control-plane-endpoint "hostname:port"

如果你想让双引号成为字符串的一部分,你可以对它进行转义

- shell: kubeadm init --control-plane-endpoint "\"hostname:port\""

,或用单引号将其结束

- shell: kubeadm init --control-plane-endpoint '"hostname:port"'

Q:*“双引号将由shell解释。对不对?“
答:对。脚本参数周围的引号的唯一作用是允许参数中有空格。比如说,

shell> cat test.sh
#!/usr/bin/sh
printf "$1\n"
printf "$2\n"

shell> ./test.sh aaa bbb ccc
aaa
bbb

shell> ./test.sh aa a bbb ccc
aa
a

shell> ./test.sh "aa a" bbb ccc
aa a
bbb

shell> ./test.sh "aa a" "bbb" ccc
aa a
bbb

shell> ./test.sh "aaa" "\"bbb\"" ccc
aaa
"bbb"

shell> ./test.sh "aaa" '"bbb"' ccc
aaa
"bbb"

相关问题