3

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!

3 Answers 3

4

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.

0
1

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.

1
  • The BashFAQ you linked to is well worth a read.
    – Mikel
    Jan 28, 2011 at 0:56
0

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"
2
  • Looks like there were other problems with the source. Missing quotes on other items, for example. Jan 27, 2011 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, 2011 at 0:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .