Sunday, February 5, 2012

Another way to run scripts from vim

0 comments
In a previous post I presented a shell script that you can call from vim using a key mapping that would run the current script you are working on in your editor session with any command line arguments specified. The script looked at the file extension and called the appropriate interpreter.

Look Here!

This is a very handy method, however, many times an executable script utility doesn't have a file extension. Without the file extension the previously present script won't work. To deal with this case, I've created another one that can be used either instead of the first or along with the first to get both cases.

My new script uses the shebang line of the script to get the interpreter. That gives me a way to launch a script utility using a key mapping in vim but I don't have to have a file extension on the file.

The script listing follows:

#!/bin/bash

# Make sure we have at least one argument
if [[ -z $1 ]]
then
    exit 1
fi

# Save our script name
script=$1

# Get the interpreter from the shebang line
interpreter=$(grep '#!/' $script | sed -r 's/(^.*?#!)//')

# Remove the first argumen
shift
args=$@

$interpreter $script $args


This script calls on a simple grep mechanism to grab the shebang line, take off the grep output with sed, to create an absolute path to an appropriate interpreter.

Take note of the '-r' option to sed. This enables us to use extended regular expressions. Your linux distro may have a different implementation of sed, so make sure to test this before you use it.

All the best.

Comments

0 comments to "Another way to run scripts from vim"