0

My sample script looks like

#!/bin/bash
VAR="foo"
if [ $VAR etc etc
then etc
...

Is there any way to call the script changing the value of $VAR without writing the script? I would imagine something like

$ bash script.sh -v VAR="bar" (sorry for the invention)

1 Answer 1

3

To set an environment variable for an invocation of a program, just add the assignment to the line before you call the script:

VAR=bar ./script.sh

Note that this won't override what is set in the script; so within the script, you will need to check if it's already set before setting it to a default value.

If you want this variable to be set for several invocations, then you can define it in your shell, and export it so that it will be in the environment of child processes:

$ export VAR=bar
$ ./script.sh
Sign up to request clarification or add additional context in comments.

1 Comment

+1. The script can set a default value if the env var is not set: : ${VAR=default-value}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.