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 ?

RDKHEN
  • 1
  • 1
    Try `source "./script.sh"`. Or, even shorter, `". ./script.sh"`. –  Apr 18 '20 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. – Charles Duffy Apr 18 '20 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. – Charles Duffy Apr 18 '20 at 18:23
  • Thank you very much for responses, it works, but unfortunately not with aliases – RDKHEN Apr 18 '20 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). – Charles Duffy Apr 18 '20 at 18:25

1 Answers1

0

You can use source instead of eval:

source "./script.sh"
Thiago Barcala
  • 6,463
  • 2
  • 20
  • 23
  • 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 Apr 18 '20 at 18:23
  • @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"). – Charles Duffy Apr 18 '20 at 18:24
  • Ok then, so I will only use scrpts since now, thank you – RDKHEN Apr 18 '20 at 18:26
  • 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. – Charles Duffy Apr 18 '20 at 18:27
  • Used source inside a function, and called it, and now I can find my variable, it's great – RDKHEN Apr 18 '20 at 18:40