【问题标题】:Output / echo string without quotation marks输出/回显不带引号的字符串
【发布时间】:2016-06-22 04:55:11
【问题描述】:

有什么方法可以在不使用单引号或双引号的情况下回显字符串。这是我的问题。

如果我有一个包含以下内容的 bash 脚本,它会按预期工作。

./node_modules/.bin/json -I -f ./test.json -e 'console.log("thomas")'

我正在尝试使用该确切代码,但我无法以任何方式更改它。我正在尝试在一个命令中将其作为字符串执行。

我尝试将 string-to-echo 用单引号和双引号括起来,但由于代码同时包含单引号和双引号,因此无法正确执行。

echo './node_modules/.bin/json -I -f ./test.json -e 'console.log("thomas")'' | sh

echo "./node_modules/.bin/json -I -f ./test.json -e 'console.log("thomas")'" | sh

有什么方法可以在一行中执行上面的代码并将其传递给sh

【问题讨论】:

  • @Cyrus 我不想逃避字符串。当它在文件中时它是有效的代码!
  • 你不能cmd | sh吗?
  • ./node_modules/.bin/json -I -f ./test.json -e 'console.log("thomas")' 的输出是什么?
  • 这个字符串可以是一个完整的 bash 文件,应该可以这样运行。 @anubhava 输出有什么关系?
  • 那你就不能用./node_modules/.bin/json -I -f ./test.json -e 'console.log("thomas")' | bash吗?

标签: bash shell unix pipe echo


【解决方案1】:

几乎可以肯定最容易转义双引号:

echo "./node_modules/.bin/json -I -f ./test.json -e 'console.log(\"thomas\")'" | sh

或者做:

sh << EOF
./node_modules/.bin/json -I -f ./test.json -e 'console.log("thomas")'
EOF

【讨论】:

    【解决方案2】:

    你可以从几个片段中拼凑出一个字符串变量:

    a='./node_modules/.bin/json -I -f ./test.json -e '
    b='console.log("thomas")'
    c=$a"'"$b"'"
    echo $c | sh
    

    编辑:糟糕,我错过了“单行”部分。我不知道你为什么想要那个,但我想你可以把它们串在一起:

    a='./node_modules/.bin/json -I -f ./test.json -e '; b='console.log("thomas")'; c=$a"'"$b"'"; echo $c | sh
    

    (如果你想让它更短一点,你可以使用echo $a"'"$b"'" 并且永远不要定义c。)

    【讨论】:

      猜你喜欢
      • 2018-07-08
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 2022-10-17
      • 1970-01-01
      • 1970-01-01
      • 2014-06-01
      • 1970-01-01
      相关资源
      最近更新 更多