How to "forward" function arguments in bash?

I am wondering how the arguments given to functions in bash can be properly "redirected" to another function or program.

For example, in Mac OS X there is an open command line program ( man page ) that will open the specified file by default (i.e. open the * .h file in Xcode or the folder in Finder, etc.). I would just call open without arguments to open the current working directory in Finder, or provide it with typical arguments for using it in normal mode.

I thought, "I'm just using a function!" Ha, not so fast, I guess. Here is what I have:

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

Just calling open works fine, it opens the working directory in Finder. Calling open myheader.h works fine, 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 the application with the name" /Applications/TextMate.app myheader.h ". It seems to transfer "$*" in /usr/bin/open causes the entire argument list to be redirected as only one argument.

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

There must be some kind of convention for sending arguments, which I just skip.

+6
source share
1 answer

You really missed the " $@ " which is for this occasion.

+10
source

Source: https://habr.com/ru/post/913672/


All Articles