Reputation: 700
I am trying to fetch a single file from Git. When I run my git command with the hardcoded value it works. 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.
#!/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 [email protected]_URL.com:help/docs.git HEAD $filePath | tar -x
Upvotes: 1
Views: 5545
Reputation: 13187
I ran into the problem recently that bash only removes quotes that did not result from variable expansion. So to get bash to remove double quotes that are in a string use eval to process the string after the variable expansion:
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.
Upvotes: 0
Reputation: 58978
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.
Upvotes: 5
Reputation: 6198
The following will work:
filePath=$(grep -o '"file-path": *"[^"]*"' ./package.json | cut -d: -f2 | tr -d ' "')
Upvotes: 0