1

I'm trying to write a bash script that can pull variables from it's execution.

I really cannot explain this very well, but I want to get a variable from the same bash script.

Let's say in this instance that the script that I wrote is CMD.sh.

sh ./CMD.sh foobar
      var = foobar

and if this is possible, how can I do this in a script?

sh ./CMD.sh foo bar fubar
      var1 = foo
      var2 = bar
      var3 = fubar

how can I create a script a bash.sh script that can pull in the variable from the above and use it

2
  • 4
    Your question isn't quite clear. Try writing an actual command line, and point us what is wrong with your solution. Commented Jul 13, 2015 at 16:23
  • Can't you first define the variables an then use them in the CMD.sh call? Commented Jul 13, 2015 at 16:43

2 Answers 2

3

You could access the arguments you've passed to a bash script as $1, $2, $3,.... i.e.: if you write a script, say my-script.sh and inside you write

echo $1
echo $2
echo $3

And you execute this script like ./my-script.sh firstarg secondarg thirdarg, then it will print:

firstarg
secondarg
thirdarg
Sign up to request clarification or add additional context in comments.

Comments

1

Probably you are talking about positional parameters.
cmd.sh:

#!/bin/bash
var1="$1"
var2="$2"
var3="$3"
echo "$var1 $var2 $var3"

$1 is the first positional parameter i.e argument passed to the script.
$2 is the second positional parameter i.e argument passed to the script.
...and so on...

Now if you run cmd.sh like this:

./cmd.sh foo bar fubar

the output will be:

foo bar fubar

Comments

Your Answer

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