0

I have a complicated bash command with some of the arguments enclosed in double quotes. When I print the command however it removes the double quotes. I know I can use the backslash \" but its just unseemly code and error prone in long commands.

Simple example:

#create folder with spaces
mydir="with space"
mkdir "${mydir}"

cmd="ls -lsa "${mydir}""
echo ${cmd}
# Wrong Output: ls -lsa with space

#now add \ before quotes
cmd="ls -lsa \"${mydir}\" "
echo ${cmd}
# Correct output: ls -lsa "with space"

Is there some other trick I can use to basically evaluate ${variable} in a string but keep the double quotes around it without resorting to using backslashes.

user603749
  • 1,638
  • 2
  • 24
  • 36
  • 3
    I suggest to use an array: `mydir="with space"; cmd=(ls -lsa "${mydir}"); "${cmd[@]}"` – Cyrus May 24 '23 at 20:37
  • 1
    Use an array as Cyrus suggested. Preserving quotes inside the variable won't fix your apparent problem because quotes inside of a variable are literal data and won't be interpreted as syntax. See: [Why does shell ignore quoting characters in arguments passed to it through variables?](https://stackoverflow.com/questions/12136948/why-does-shell-ignore-quoting-characters-in-arguments-passed-to-it-through-varia) – tjm3772 May 24 '23 at 20:40
  • If you're not attempting to preserve quotes to make a command work, the "clean" workaround would be to assign with single quotes - for example `insert="some quotes" ; myvar='I have "'$insert'" in me' ; echo $myvar` will print `I have "some quotes" in me` – tjm3772 May 24 '23 at 20:49
  • @tjm3772: I suggest to add two `"` in `myvar='I have "'"$insert"'" in me'` to keep multiple consecutive spaces in `$myvar`. – Cyrus May 24 '23 at 21:20
  • 1
    See [BashFAQ/050 (I'm trying to put a command in a variable, but the complex cases always fail!)](https://mywiki.wooledge.org/BashFAQ/050) and [How can I store a command in a variable in a shell script?](https://stackoverflow.com/q/5615717/4154375). – pjh May 24 '23 at 21:24
  • @Cyrus I tested your suggestion and it does not do what I asked which is the preservation of the double quotes around the ${variable}. I will be using ```\"``` and just live with it. – user603749 May 27 '23 at 19:13

0 Answers0