Open tkeith opened 6 months ago
try echo "foo \\ bar"
.
try
echo "foo \\ bar"
.
Yes, of course this correctly prints foo \ bar
, but how would I programmatically derive "foo \\ bar"
from shell-quote
's result of 'foo \\ bar'
?
This package returns a string; the bounding quotes aren't part of it, so you just always include them.
Quoting the string foo \ bar
via quote(["foo \\ bar"])
returns the literal string 'foo \\ bar'
, which already includes bounding single quotes. So if this is intended to be used within double quotes, the echo statement would be echo "'foo \\ bar'"
, which still prints an incorrect result, 'foo \ bar'
.
ah, sorry, early morning here.
i'll take another look at this issue when i'm more awake.
Thank you -- still quite possible I'm misunderstanding how to use it correctly.
My comparison points are Python's shlex.quote
and Linux's printf "%q"
, which both seem to be quoting/escaping the input strings "correctly" by my definition (returning strings that when passed to echo
in bash, print the originally passed-in string).
This has led me to the following temporary solution for JavaScript on Unix-based systems (I'm aware that this is hugely non-performant given the use of spawn
):
import { spawnSync } from "child_process";
export default function quote(rawInput: string): string {
const result = spawnSync("printf", ["%q", rawInput], { encoding: "utf8" });
if (result.status === 0) {
return result.stdout;
} else {
throw new Error(
`printf failed with code ${result.status} and error: ${result.stderr}`,
);
}
}
I might be misunderstanding the intended usage of shell-quote, but it seems like strings containing both backslashes and spaces are not handled properly:
Let's consider the string
foo \ bar
.quote(["foo \\ bar"])
returns'foo \\ bar'
, and in bash,echo 'foo \\ bar'
printsfoo \\ bar
.This failure case does not occur with the same string without spaces (
foo\bar
):quote(["foo\\bar"])
returnsfoo\\bar
, and in bash,echo foo\\bar
printsfoo\bar
.Here's a quick typescript file to reproduce with a few test cases:
The output of running that file is: