Search code examples
bashvimquoting

Bash: how to store multiple options in a string?


Within a bash script, I launch Vim with options:

vim "-c startinsert" "+normal 2G4|" foo  

double-quotes are needed, but it could be replaced by simple one:

vim '-c startinsert' '+normal 2G4|' foo  

as those options could vary from one file to another, I want to store them in a string, typically:

opt='"-c startinsert" "+normal 2G4|"'  

and then:

vim $opt foo  

but that does not work, and I tried every combination of quotes, double-quotes, escaping,…

Actually, the only way I find it works is to store only one option per string:

o1="-c startinsert"  
o2="+normal 2G4|"  
vim "$o1" "$o2" foo

So, is it possible to store two (or more) options in a string? Because when I tried, bash seems to interpret them as a file name, for example:

opt='"-c startinsert" "+normal 2G4|"'  
vim "$opt" foo  

Vim will open two files:

  1. ""-c startinsert" "+normal 2G4|""
  2. foo

instead of open foo with options "-c startinsert" "+normal 2G4|".


Solution

  • I suggest using arrays, which you can manipulate easily and even use some substitutions when expanding.

    Also, note that -c is equivalent to beginning a command directly with +.

    opt=(startinsert 'normal 2G4|')
    # opt+=('normal l')
    vim "${opt[@]/#/+}" foo
    

    The last line automatically prepends + to each argument.