bash脚本执行命令带有双引号,单引号和空格 [英] bash script execute command with double quotes, single quotes and spaces

查看:68
本文介绍了bash脚本执行命令带有双引号,单引号和空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过有关此问题的类似文章,但无法弄清楚如何使执行的代码具有正确的格式,该格式必须为 foo --bar"a ='b'".我对此的最佳尝试是

I've looked at the similar posts about this problem, but cannot figure out how to get the executed code to be in the correct format, which needs to be foo --bar "a='b'". My best attempt at this was

#!/bin/bash -x

bar='--bar ''"''a='"'"'b'"'"'"'
cmd=(foo $bar)
echo ${cmd[@]}
eval ${cmd[@]}

此输出对于 echo 是正确的,但对于 eval

The output from this is correct for the echo, but incorrect for eval

+ bar='--bar "a='\''b'\''"'
+ cmd=(foo $bar)
+ echo foo --bar '"a='\''b'\''"'
foo --bar "a='b'"
+ eval foo --bar '"a='\''b'\''"'
++ foo --bar 'a='\''b'\'''

使用该选项执行命令的正确方法是什么?

What is the correct way to execute the command with the option?

推荐答案

如果必须存储命令片段,请使用函数或数组,而不要使用字符串.

根据 BashFAQ#50 的最佳实践代码示例:

If you must store command fragments, use functions or arrays, not strings.

An example of best-practice code, in accordance with BashFAQ #50:

#!/usr/bin/env bash
bar=( --bar a="b" )
cmd=(foo "${bar[@]}" )
printf '%q ' "${cmd[@]}" && echo  # print code equivalent to the command we're about to run
"${cmd[@]}"                       # actually run this code


奖金:您的调试输出无法证明您的想法.

"a ='b'" 'a ='\'b'\'''是引用完全相同的两种不同方式字符串.

要证明这一点:

printf '%s\n' "a='b'" | md5sum -
printf '%s\n' 'a='\''b'\''' | md5sum -

...作为输出发出:

...emits as output:

7f183df5823cf51ec42a3d4d913595d7  -
7f183df5823cf51ec42a3d4d913595d7  -

...因此,在代码中解析 echo $ foo eval $ foo 的参数之间没有什么不同.

...so there's nothing at all different between how the arguments to echo $foo and eval $foo are being parsed in your code.

为什么这是真的?因为语法引号不是实际运行的命令的一部分;在外壳程序使用它们确定如何逐个字符解释命令行后,它们将被外壳程序删除.

Why is this true? Because syntactic quotes aren't part of the command that's actually run; they're removed by the shell after it uses them to determine how to interpret a command line character-by-character.

因此,让我们分解一下 set -x 向您显示的内容:

So, let's break down what set -x is showing you:

'a='\''b'\'''

...由以下串联在一起的文字字符串组成:

...consists of the following literal strings concatenated together:

  • a = (在单引号上下文中,输入并以单引号引起来)
  • '(在未引用的上下文中,由其前面的反斜杠转义)
  • b (在单引号上下文中,以单引号引起并在其周围加上单引号)
  • '(在未引用的上下文中)
  • a= (in a single-quoted context that is entered and ended by the single quotes surrounding)
  • ' (in an unquoted context, escaped by the backslash that precedes it)
  • b (in a single-quoted context that is entered and ended by the single quotes surrounding)
  • ' (in an unquoted context)

...其他所有内容都是 syntactic ,对shell有意义,但从未传递给程序 foo .

...everything else is syntactic, meaningful to the shell but not ever passed to the program foo.

这篇关于bash脚本执行命令带有双引号,单引号和空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆