简体   繁体   English

从bash中的字符串中删除双引号

[英]Remove Double Quotes from a String in bash

I am trying to fetch a single file from Git.我正在尝试从 Git 获取单个文件。 When I run my git command with the hardcoded value it works.当我使用硬编码值运行我的 git 命令时,它可以工作。 However, when I run it with a variable it breaks.但是,当我使用变量运行它时,它会中断。 I suspect it is due to double quotes being placed around my variable somehow.我怀疑这是由于以某种方式在我的变量周围放置了双引号。 I have tried many commands to remove the double quotes from the string and none of them seem to work.我已经尝试了很多命令来从字符串中删除双引号,但它们似乎都不起作用。

I am basically trying to use the filePath variable in my git command with no double quotes around it.我基本上是尝试在我的 git 命令中使用 filePath 变量,而它周围没有双引号。

#!/usr/bin/env bash
 #reads the JSON value of the file-path key. 
 #file path key is "home/docs" (quotes included)
filePath=$(grep -o '"file-path": *"[^"]*"' ../package.json | grep -o '"[^"]*"$')
git archive --remote=git@git.SOME_URL.com:help/docs.git HEAD $filePath | tar -x

This works:这有效:

$ printf '{"file-path": "/some/path"}' | jq --raw-output '."file-path"'
/some/path

So in your case:所以在你的情况下:

filePath=$(jq --raw-output '."file-path"' ../package.json)

You have to quote the key because it contains a hyphen.您必须引用该键,因为它包含一个连字符。

I ran into the problem recently that bash only removes quotes that did not result from variable expansion.我最近遇到了一个问题,即 bash 只删除不是由变量扩展引起的引号。 So to get bash to remove double quotes that are in a string use eval to process the string after the variable expansion:因此,要让 bash 删除字符串中的双引号,请使用 eval 在变量扩展后处理字符串:

foo=\"abc\"\ \"def\"
echo $foo
"abc" "def"
eval echo $foo
abc def

Of course, don't use eval on unsanitised strings from users, as it is susceptible to ';', '&&', etc. to execute arbitrary bash.当然,不要对来自用户的未经处理的字符串使用 eval,因为它容易受到 ';'、'&&' 等的影响来执行任意 bash。

以下将起作用:

filePath=$(grep -o '"file-path": *"[^"]*"' ./package.json | cut -d: -f2 | tr -d ' "')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM