0

I know this question might sound familiar and may be similar to other questions like how to escape quotes in command argument to sh -c? and many others. But none of the methods marked as answer to these question work for me. So, please bear with me.

I am trying to send a command to another terminal. I've learned that I need to use sh -c to send the entire command in once. The command itself is to compress a file using 7z. Here is an example:

7z a Aa.zip Bb.txt

so the entire command would be

sh -c '7z a Aa.zip Bb.txt'

This works without any issue. The problem is when there is single quote (') in the filename to be compressed, e.g. B'b.txt. So, the command becomes

sh -c '7z a Aa.zip B'b.txt'

which does not run in terminal.

These are the commands that I tried with no luck:

sh -c '7z a Aa.zip B'b.txt'
sh -c '7z a Aa.zip B\'b.txt'
sh -c '7z a Aa.zip B'"'"'b.txt'
sh -c '7z a Aa.zip "B'b.txt"'
sh -c '7z a Aa.zip \"B\'b.txt\"'
sh -c '7z a Aa.zip \"B'b.txt\"'
sh -c '7z a Aa.zip B'\''b.txt'

Running these commands result in either this error:

Syntax error: Unterminated quoted string

or waiting for input

>

which I then cancel using Ctrl+c.

I also tried using a variable and then pass it to sh -c. Again with no luck:

cmd="'7z a Aa.zip B'b.txt'"
echo $cmd
'7z a Aa.zip B'b.txt'
sh -c $cmd
a: 1: a: Syntax error: Unterminated quoted string

Please let me know what I am doing wrong?

NESHOM
  • 889
  • 14
  • 42

3 Answers3

2

You're looking for:

sh -c '7z a Aa.zip "B'\''b.txt"'

This: '\'' is an escaped ' as a part of the string. You need that for the sh command itself. Once you've started running the command, leaving the ' unmatched causes a problem, so you need to put it inside of a string.

cwallenpoole
  • 76,131
  • 26
  • 124
  • 163
0

I'll suggest reading through this shell command language article. For your case, specifically

"A backslash cannot be used to escape a single-quote in a single-quoted string. An embedded quote can be created by writing, for example: "'a'\''b'", which yields "a'b". A single token can be made up of concatenated partial strings containing all three kinds of quoting or escaping, thus permitting any combination of characters."

Hope it'll work for you.

cecky
  • 51
  • 4
0
sh -c "7z a Aa.zip B'b.txt"

or

sh -c '7z a Aa.zip B'"'"'b.txt'

Or just, you know, use a (bash or zsh) array.

cmd=(7z a Aa.zip B'b.txt)
sh -c "${cmd[@]}"
Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325