Search code examples
bashbash-function

accessing script parameter from bash function without passing them on call


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

Thanks.


Solution

  • 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 "$@"
    }