Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 261
inspector-g Avatar asked Apr 20 '12 01:04

inspector-g


People also ask

How do you pass an argument to a function in shell script?

Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth. The variable $0 references to the current script.

What does $@ do bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

What does $() mean in bash?

Example of command substitution using $() in Linux: Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).


1 Answers

You indeed missed "$@", which is designed for this case.

like image 196
geekosaur Avatar answered Sep 21 '22 13:09

geekosaur