Pregunta

Is there any way to access bash script parameters from script function if the function is not explicitly called with script parameters?

Thanks.

¿Fue útil?

Solución

No, but you can hack it if you are on Linux by reading your script's command-line from `/proc':

function myfunc {

    while read -d $'\0' 
    do 
        echo "$REPLY"
    done < /proc/$$/cmdline
}

The -d $'\0' is required to read the cmdline file because the strings are NULL (binary zero) delimited. In the example, $REPLY will be each parameter in turn, including bash itself. For example:

/home/user1> ./gash.sh one two three
/bin/bash
./gash.sh
one
two
three

Here is an example which will set the function's parameters to those of the script (and display them):

function myfunc {

    while read -d $'\0' 
    do
        args="$args $REPLY"
    done < /proc/$$/cmdline

    set -- $args
    shift 2      # Loose the program and script name
    echo "$@"
}

Otros consejos

The short answer is "No, not that I know of."

If it had to be done I'd alias the script arguments.

#!/bin/bash
script_args=("$@")
myfunc () {
    for a in "$@" ; do
        for b in "${script_args[@]}" ; do
            echo "$a: $b"
        done
    done
}

myfunc one two

And then call like this:

./myscript.sh 1 2

Output:

one: 1
one: 2
two: 1
two: 2

Just call the function with the script's arguments.

foo () {
    for arg in "$@"
    do
        echo "$arg"
    done
}

foo "$@"
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top