26 Feb 2012 Kay   » (Journeyer)

Shell scripts and space characters in command line parameters

I'm using Linux for more than 10 years now and it is embarrassing that I missed this shell feature for so long. But first let's explain the problem: Let's say we want to write a shell script which simply starts some application and which passes all command line parameters to this application. This is often useful if an application is installed in some directory which is not in the PATH and you want to put a starter script into ~/bin which is in PATH. Example:

#!/bin/sh
# Filename: ~/bin/startmyapp
cd ~/opt/myapp
exec ./myapp $*

$* is a place holder for all command line parameters which were passed to this shell script. Now let's feed some command line parameters to it:

startmyapp arg1 "arg2 with spaces" arg3

The ~/opt/myapp/myapp program is now called like this from the shell script:

./myapp arg1 arg2 with spaces arg3

So now there are five parameters instead of three. Bad thing. Using "$*" instead of $* also doesn't work because then all command line parameters are passed as a single parameter to the program. So far I never searched for a solution to this problem. Instead I always worked around this problem somehow. But today I took some time to find a solution and found it pretty fast. It simply looks like this:

#!/bin/sh
# Filename: ~/bin/startmyapp
cd ~/opt/myapp
exec ./myapp "$@"

This $@ parameter was completely new to me. The difference between $* and $@ is explained here.

Syndicated 2012-02-26 15:41:34 from K's cluttered loft

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!