Thursday, April 19, 2012

How does one properly "forward" function arguments in bash?

I am wondering how arguments given to a function in bash can be properly "forwarded" to another function or program.



For example, in Mac OS X there is a command line program open (man page) that will open the specified file with its default application (i.e. it would open a *.h file in Xcode, or a folder in Finder, etc). I would like to simply call open with no arguments to open the current working directory in Finder, or provide it the typical arguments to use it normally.



I thought, "I'll just use a function!" Hah, not so fast there, I suppose. Here is what I've got:



function open
{
if [ $# -eq 0 ]; then
/usr/bin/open .
else
/usr/bin/open "$*"
fi
}


Simply calling open works great, it opens the working directory in Finder. Calling open myheader.h works great, it opens "myheader.h" in Xcode.



However, calling open -a /Applications/TextMate.app myheader.h to try to open the file in TextMate instead of Xcode results in the error "Unable to find application named ' /Applications/TextMate.app myheader.h'". It seems passing "$*" to /usr/bin/open is causing my entire argument list to be forwarded as just one argument instead.



Changing the function to just use usr/bin/open $* (no quoting) causes problems in paths with spaces. Calling open other\ header.h then results in the error "The files /Users/inspector-g/other and /Users/inspector-g/header.h do not exist", but solves the other problem.



There must be some convention for forwarding arguments that I'm just missing out on.





No comments:

Post a Comment