0

I cannot find anything about how to import a single variable into a bash script. Is importing a variable from another file the only way to do this? I imagine I would create a temporary file temp.txt that had the line...

MYTEMPVAR=something

I would like to be able to trigger the bash script from a form, so every time the bash script was called it would have a different value. Can this be done?

4
  • 5
    What is your ultimate goal? Tell us what you're trying to do so we can avoid an XY problem. There are many, many ways to pass values to scripts. Command-line arguments, standard input, sourcing config files, etc. Commented May 29, 2018 at 16:05
  • 1
    What is your algorithm for "every time the bash script was called [the variable] would have a different value"? It kind of sounds like that should be built into the script itself instead of relying on an external resource. Commented May 29, 2018 at 16:07
  • this is usually done with "sourcing" the parameter files within the script. Commented May 29, 2018 at 16:25
  • Thanks for the comments. It's a script for making a new linux user and doing some other related tasks. So, I have an HTML form and I want to complete the form with the username, and maybe password. Obviously, these couldn't be hard-coded into the script. I should also say that the script will be called by PHP. Commented May 29, 2018 at 21:10

2 Answers 2

4

You can specify variables inline when running a bash script. Contents of var.sh:

#!/bin/bash

echo "The date is $mydate"

Command:

$ mydate="Tuesday 29th" ./var.sh
The date is Tuesday 29th

$ mydate=$(date) ./var.sh
The date is 29 May 2018 17:27:39
Sign up to request clarification or add additional context in comments.

Comments

0

The problem with running another script with a variable setting, is that by default this is done in a subprocess. The parent shell will be unaware of environment variables (or current durectory) in the subprocess.
What you need, is starting that script without an extra process. You can tell bash to run the script in the current environment with source otherscript or shorter . otherscript.
Try the next commands:

mytempvar="inital value" # variable in lowercase, uppercase is reserved for the shell
echo "mytempvar=something" > temp.sh
chmod +x temp.sh
./temp.sh # starts in a subprocess, the changed value is lost
echo "${mytempvar}"
source temp.sh # run it in the current shell
echo "${mytempvar}"
mytempvar="new value"
. temp.sh # Just like source, other syntax
echo "${mytempvar}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.