Pass an empty command line through to a source'd script

Viewed 38

My bash script expects command line arguments that I parse without any problem. However the script later calls an other script which also accepts positional parameters, but providing parameters is not mandatory.

When my script sources the other script without arguments the other script still tries to parse those arguments that were given to my script in the first place.

I have two solutions, but none of them looks good to me.

  1. With shift:

    # now making this script to handle branches:
    OPTIND=1
    while getopts "b:" opt; do
        case "$opt" in
            'b' ) branch=$OPTARG ;;
        esac
        shift
    done
    
  2. Passing empty argument to the second script:

    source ${MINICONDA}/bin/activate ""
    
1 Answers

Note that this isn't needed for normal calls of a script as an external process, but only for invocations with source or ..

To provide context to readers, from bash's built-in help to source:

If any arguments are supplied, they become the positional parameters when filename is executed. Otherwise the positional parameters are unchanged.


The easiest way to control the argument list is using set -- arg1 arg2 ... to immediately overwrite it with a new list. Thus:

orig_args=( "$@" )        # back up the original arguments
set --                    # clear the argument list

source whatever

set -- "${orig_args[@]}"  # if you ever need them back
Related