lavalade
lavalade

Reputation: 368

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|".

Upvotes: 0

Views: 508

Answers (2)

sidyll
sidyll

Reputation: 59277

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.

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246744

See I'm trying to put a command in a variable, but the complex cases always fail!

Use an array

opts=(
    -c "startinsert" 
    "+normal 2G4|"
)  
vim "${opts[@]}" foo  

Upvotes: 4

Related Questions