Change the install behavior by setting variables when running the script



  • I've discovered that you can change the install behavior of a variable while running a script.

    #!/usr/bin/env bash
    
    # Default settings
    VAR1=${VAR1:-~/examples/hello-world}
    
    # Create /home/user/examples/hello-world directory
    mkdir --parents "$VAR1"
    

    By default when you run this script, it will create hello-world directory in /home/user/examples. But let's say you want to create the hello-world directory in /home/user/.

    You can achieve this by adding VAR1= before the bash command:

    Example 1 - Running a script locally

    VAR1=~/hello-world bash hello-world.sh

    Example 2 - Running a script directly from a website.

    VAR1=~/hello-world bash -c "$(curl -fsSL https://example.com/demo.sh"



  • The special sauce in the script is a form of conditional expression.

    VAR1=${VAR1:-~/examples/hello-world}
    means that VAR1 will be set to ~/examples/hello-world if it's not already set.

    Can also be done with if...then like this:
    if [[ -z ${VAR1} ]]; then VAR1=~/examples/hello-world; fi

    This is the conditional expression:
    ${VAR1:-SOMETHING}

    It means if VAR1 is null the return SOMETHING else return VAR1

    PS. Your title is a little misleading. The only thing that happens is if you set the variable VAR1 before executing the script, it will use that value instead of the default inside the script.



  • What's this all about? Script parameters?



  • @Obsolesce said in Change the install behavior by setting variables when running the script:

    What's this all about? Script parameters?

    Kind of. To be very specific it's local environment variables.

    You set them before running the script and can use them in scripts but if you restart the shell they are gone.


    Parameters are those variables that are assigned from the command line. They are referred to as $1 $2 $3 etc inside the script.

    So if you do run hello-world.sh ~/examples/hello-world
    Inside the script $1 will then be set to '~/examples/hello-world'.



  • @Pete-S said in Change the install behavior by setting variables when running the script:

    You set them before running the script and can use them in scripts but if you restart the shell they are gone.

    Besides probably losing whatever was running in your current shell session, is there any benefits of adding exec $SHELL at the end of a script file?


Log in to reply