Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Background

Control whether row numbers are displayed after vim starts (in a non-interactive mode).

Problem

A shell script contains the following code:

echo Converting $1 to $1.html...

NUMBERS="-c set number"
if [ "$2" == "" ]; then
  NUMBERS=
fi

vim -e $1 -c "set nobackup" $NUMBERS -c ":colorscheme moria" \
  -c :TOhtml \
  -c wq  -c :q

The script (src2png.sh) is invoked as:

./src2png.sh src2png.sh

And also invoked as:

./src2png.sh src2png.sh numbers

In the second case, vim should be started with numbers along the left-hand side. (The word "numbers" can be anything, so long as it is not empty.) I have tried several syntactical variations without success:

NUMBERS=-c "set number"
NUMBERS="-c set number"
NUMBERS="-c 'set number'"
NUMBERS="-c \":set number\""

All of these fail when starting vim, for various reasons. (Usually, "Error detected while processing command line:".)

Question

What is the correct syntax to allow a second command-line parameter to control whether or not vim starts with row numbers displayed?

Thank you!

share|improve this question

3 Answers 3

up vote 4 down vote accepted

Try this:

vim -e $1 -c "set nobackup" ${2:+"-c set number"} -c "colorscheme moria" \
-c TOhtml \
-c wq -c q

See the bash(1) man page, the section on Parameter Expansion for an explanation of how that works.

share|improve this answer
    
Thank you. Nice use of parameter expansion. –  Dave Jarvis Jan 28 '11 at 0:12

Try setting NUMBERS to an array:

NUMBERS=(-c set number)

or use NUMBERS as a flag and do:

NUMBERS=flag
if [ "$2" == "" ]; then
    NUMBERS=
fi

vim -e $1 -c "set nobackup" ${NUMBERS:+-c set number} -c ":colorscheme moria" \

Please see also BashFAQ/050.

share|improve this answer
    
The BashFAQ you linked to is well worth a read. –  Mikel Jan 28 '11 at 0:56

A simple hack would be to use sh -c, like so:

NUMBERS="-c ':set number'"
sh -c "vim $NUMBERS"

This does start another shell process, so if you're worried about overhead, instead you might try having $NUMBERS either contain ":set number" or a no-operation like ":", thus:

vim -c "$NUMBERS"
share|improve this answer
    
Looks like there were other problems with the source. Missing quotes on other items, for example. –  Dave Jarvis Jan 27 '11 at 23:23
    
Instead of sh -c "vim $NUMBERS" you could use eval vim $NUMBERS. Then you wouldn't be spawning another process. You do have to be careful about how eval transforms your other arguments, though. –  garyjohn Jan 28 '11 at 0:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.