Declare a variable to a bash script runtime

In the past I’ve did a post about checking if a bash argument is set.
This is different, This way you can pass through a named variable.

    TEST='pass it on' ./testscript.sh

If you do this $TEST will be set inside the ./testscript.sh bash script.
Like the normal arguments you probably would like to validate them inside the bash script.
The main plus side is that you can put arguments in any order and exclude arguments.
It might also be easier to read as you can see the arguments name.

A bit more advanced. You can override global variables for that script run.
Variables like $PWD and $PATH, be careful.

Example script: ./testscript.sh

#!/usr/bin/env bash

if [ ! -z $TEST ]; then
    echo "var is set to '$TEST'";
else
    echo "var is unset";
fi

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.