1

I would like to get the same effect as vim "$p", but without using double quotes, where $p is a path with special characters and spaces.

e.g. something a desirable DOUBLE_QUOTE function: vim $(DOUBLE_QUOTE $p)

After lots of reasearch I tried:

  • vim $(echo ${p@Q})

...all with no success (I get quotes showing up in the path)

Background: The reason is the string is passed between a few window batch scrips, and programs, and I have spent the weekend trying to escape the double quotes through multiple layers with no success.

run_the_race
  • 1,344
  • 2
  • 36
  • 62
  • 2
    You could make a symlink called `it` with `ln - s "weird thing with spaces" it` and then do `vim it` – Mark Setchell Jul 12 '20 at 14:49
  • What do you do with the script? Why exactly the double quotes don't meet your needs? – MichalH Jul 12 '20 at 14:56
  • 2
    Why not use double quote? If you call ```myScript.sh "a b c"```, inside the sccript the variable ```$1``` has the value without quotes. Then you can pass it on to the next script by inside the ```nextScript.sh "$1"```. – Donat Jul 12 '20 at 15:35
  • 3
    Ask about your *actual* problem, not what you think is the solution to that problem. – chepner Jul 12 '20 at 15:42
  • If one of the special characters is `#` you will have a tough time without using double-quote. – stark Jul 12 '20 at 15:54
  • @stark, That's not a problem. It's whitespace that consists of anything but a single space that's the problem. – ikegami Jul 12 '20 at 17:00

1 Answers1

4

After doing

IFS=

You can use

vim $p

Otherwise, no.


With the default value of IFS, bash will split the value of $p on sequences of spaces, tabs and/or linefeeds. That will make it impossible to send a␠␠b (two spaces in the middle) to DOUBLE_QUOTE, and DOUBLE_QUOTE would be unable to distinguish a␠b (spaces in the middle) from a␉b (tab in the middle).

Furthermore, the value returned by DOUBLE_QUOTE would also be subject to this splitting.

As such,

vim $( DOUBLE_QUOTE $p )

would have to be

vim "$( DOUBLE_QUOTE "$p" )"

to work with the default value of IFS.


If, on the other hand, you are trying to generate shell commands, you can look at this question's answers for help.

For example,

printf '%s\n' "$( quote vim "$p" )"

outputs

'vim' 'a  b'

given

p='a  b'

and

# quote() - Creates a shell literal
# Usage:  printf '%s\n' "$( quote "..." "..." "..." )"
quote() {
    local prefix=''
    local p
    for p in "$@" ; do
        printf "$prefix"\'
        printf %s "$p" | sed "s/'/'\\\\''/g"
        printf \'
        prefix=' '
    done
}
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • IFS= did the trick, thank you so much!!! I also eventually figured out to get a " to appear in the final script, I needed to send \\"^"" but your way is much cleaner. – run_the_race Jul 13 '20 at 06:31