Ubuntu – Pass variables to script which called script

bashcommand linescripts

I have a bash script which must call another bash script which varies per-user in order to get some configuration information, like so:

somescript:

#!/bin/bash
${HOME}/.ssconfig
echo "Hello, ${VARIABLE}!"

~/.ssconfig

#!/bin/bash
VARIABLE=world

Which, instead of giving me Hello, world! as expected, gives me Hello, !
How can I pass variables up from a script to the one that called it?

Best Answer

  • Executing a script cannot affect the shell that called it, since the script runs in its own shell. To affect the calling shell, you need to source the script:

    $ help source  
    source: source filename [arguments]  
        Execute commands from a file in the current shell.
    
        Read and execute commands from FILENAME in the current shell.  The
        entries in $PATH are used to find the directory containing FILENAME.
        If any ARGUMENTS are supplied, they become the positional parameters
        when FILENAME is executed.
    

    Hence, the line where you execute the configuration file should be changed to source it:

    #!/bin/bash
    source ${HOME}/.ssconfig
    echo "Hello, ${VARIABLE}!"
    

    Note that source is a shell command, so the help for it is not in man source, but help source.