Bourne shell: send arguments from $ 2 to $ N to a variable function?

Google finally let me down. I cannot find how to do this in Bourne shell scripts:

I am writing a shell script to handle all of my tests for a project. I created functions for each task that this script could perform (build, run, clean up, etc.), and I would like to pass any additional command line parameters (besides the command itself) to the desired function.

Example:

./test.sh build -j should pass -j to the build function.

The pseudocode version of this logic will look like this:

 function build() { make $* } if [ $1 == 'build' ]; then build $2 -> $N fi 

How can i do this?

+7
source share
3 answers

I think you could achieve this effect with the shift command. It will shift all positional parameters by one place and lower the value of $1 (therefore, the value of $3 will be transferred to $2 , the value of $2 will be transferred to $1 , and the value of $1 lost). Once you do this, you can simply use $@ to select a list of arguments that you are really interested in, for example.

 function build() { echo "build with $@ " } echo "Starting args are $@ " cmd=$1 shift if [ "$cmd" = 'build' ]; then build " $@ " fi 
+9
source
 function build() { make " $@ " } if [ "$1" == 'build' ] then shift # Lose $1 build " $@ " # Pass what was $2 .. $N fi 

Pay attention to the use of " $@ " both in the function itself and when calling the function. I would say that it is rarely the case to use either $* or $@ without double quotes or "$*" ; only " $@ " retains the spacing of the original argument list, which matters if you have arguments containing spaces. If you are going to repeat the arguments, then echo "The arguments: $*" is reasonable. Otherwise, in more than 90% of cases, you are better off using " $@ " . I also take an extremely conservative attitude towards quoting "$1" in a test statement; Be careful to exclude quotation marks.

See also:

+5
source

If you do not want to generate a more detailed error message, there is no need to explicitly check $1 . Just do:

 #!/bin/sh -e function build() { make " $@ " } " $@ " 

If $1 calls a valid function, it will be called as desired. If this is not the case, you will receive an error message, which is probably not so bad, depending on your shell.

+2
source

All Articles