Shell scripts and space characters in command line parameters

Sunday, February 26. 2012

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.

Posted in Linux | Comments (0)

Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.