从bash脚本引用sed执行

时间:2018-09-30 20:53:38

标签: bash escaping double-quotes quoting single-quotes

我正在尝试将一个sed命令转换为bash执行,但是遇到了无法用引号或变量扩展识别的问题。

直接从控制台中的工作命令

BASH> diff vault-config.rb vault-config.rb.backup
BASH> sed -n -r -i '/^.*vault_config.*resource.*$/{x;s/\n//p;x;p;s/.*//;h};//!H;${x;s/.*/# Insert File_109 vault for node n109\n$vault_config['"'"'resource'"'"']['"'"'File_109'"'"'] = '"'"'\/tmp\/File_109.json'"'"'\0/p}' "/tmp/vault-config.rb"
BASH> diff vault-config.rb vault-config.rb.backup
208,209d207
< # Insert File_109 vault for node n109
< $vault_config['resource']['File_109'] = '/tmp/File_109.json'

不工作尝试转换为bash脚本(具有某些模块化)

BASH> NODE="n109"
BASH> VAULT_ID="File_109"
BASH> VAULT_FILE="/tmp/File_109.json"
BASH> VAULT_RESOURCE="\$vault_config['resource']['File_109'] = '/tmp/File_109.json'"
BASH> VAULT_CONFIG_FILE="/tmp/vault-config.rb"

BASH> echo "DEBUG: NODE ${NODE}"
DEBUG: NODE n109
BASH> echo "DEBUG: VAULT_ID ${VAULT_ID}"
DEBUG: VAULT_ID File_109
BASH> echo "DEBUG: VAULT_FILE ${VAULT_FILE}"
DEBUG: VAULT_FILE /tmp/File_109.json
BASH> echo "DEBUG: VAULT RESOURCE ${VAULT_RESOURCE}"
DEBUG: VAULT RESOURCE $vault_config['resource']['File_109'] = '/tmp/File_109.json'
BASH> echo "DEBUG: VAULT_CONFIG_FILE ${VAULT_CONFIG_FILE//"/"/\/}"
DEBUG: VAULT_CONFIG_FILE \/tmp\/vault-config.rb

BASH> args=("-n" "-r" "-i" "'/^.*vault_config.*resource.*\$/{x;s/\\n//p;x;p;s/.*//;h};//!H;\${x;s/.*/#This is automated insert of key ${VAULT_ID} vault for node ${NODE}\\n${VAULT_RESOURCE}\\0/p}'" "${VAULT_CONFIG_FILE//"/"/\/}")
-bash: !H: event not found
BASH> #sed "${args[0]}" # <-- commented because previous command is failing

分配给args后的结果为-bash: !H: event not found。我在args元素和变量VAULT_RESOURCE中尝试了各种形式的转义,因为我认为args可能不喜欢其中的单引号。

当我转义!\!时,args命令停止失败,但是sed失败了,在这种情况下args似乎仅包括前三个参数。

使用此命令已经花费了几个小时后,我的结论是,我得到的错误与真正的错误无关,并且根据文档!,后台中有某些内容不需要在其中转义双引号,但现实不一样

BASH> TEST="Test string !H"
-bash: !H": event not found
BASH> TEST="Test string \!H"
BASH> echo $TEST
Test string \!H

一种解决方法是将这个命令放入临时.sh脚本并调用该脚本,但我不喜欢它。

我做错了什么? 感谢您的帮助

0 个答案:

没有答案