0

I want to use a variable initialized into a subscript, in order to avoid returning it with echo or return.

For example, my goal is to output $myvar with this script:

eval "./script.sh"
echo -n $myvar

declared inside script.sh like this:

declare -gx myvar # global and exported var
myvar=42

Output:

nothing

Is there another command or flag to add in replacement to declare -gx ? Or moving it before eval is the solution ?

5
  • 1
    Try source "./script.sh". Or, even shorter, ". ./script.sh". Commented Apr 18, 2020 at 18:19
  • To make eval do you wanted, it'd need to be eval "$(<./script.sh)", or eval "$(cat ./script.sh)" -- but those are both very silly, as source Does The Right Thing out-of-the-box. Commented Apr 18, 2020 at 18:22
  • BTW, you don't need the declare -gx at all here. declare -g is only needed when you're inside a function. declare -x is only needed when you want the variable exported to subprocesses. Neither situation applies. Commented Apr 18, 2020 at 18:23
  • Thank you very much for responses, it works, but unfortunately not with aliases Commented Apr 18, 2020 at 18:24
  • Nobody should ever use aliases. They're worse than shell functions in every way. (There are actually some exceptions, but if you're not enough of an expert to already know what they are, they don't apply to you). Commented Apr 18, 2020 at 18:25

1 Answer 1

0

You can use source instead of eval:

source "./script.sh"
Sign up to request clarification or add additional context in comments.

5 Comments

It works great thanks, but now what if I need to use a script with an alias ? The source command does not match aliases
@RDKHEN, by default, aliases don't work inside scripts at all. (There's a reason the freenode #bash channel advice about aliases is "if you need to ask, use a function instead").
Ok then, so I will only use scrpts since now, thank you
You don't need to only use scripts. Shell functions serve the use case aliases do, but do so more effectively; and they work the same way in your interactive shell (f/e, defined in .bashrc) as they do in a script.
Used source inside a function, and called it, and now I can find my variable, it's great

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.