1

I need make something like

$ source /etc/environments # called in bash.sh script

Of course after script finished no changes apply to shell. I know this is tricky if because child process cant modify parent 'bash' process. But May be another way to do so?

Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
M_F
  • 406
  • 7
  • 16

2 Answers2

3

You should use

source bash.sh

Then it runs in the original shell instead of a child process.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

As you have observed yourself a child process cannot set persistent environment variables. One of the usual work around are writing something like this to stdout:

% cat my_script
#!/bin/bash
echo "export MY_VAR=1234"

And then used in a command substitution:

eval "$(./my_script)"

An example of such script is dircolors

Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
  • @123 It will work with bash scripts, but nothing else. – Andreas Louv Jun 07 '16 at 10:05
  • I ment that `my_script` needs to be written in the same language as where it's sourced, and no `$(...)` is not bash only. – Andreas Louv Jun 07 '16 at 10:10
  • I meant not portable,not just bash, sorry. But this still doesn't make any sense to do, – 123 Jun 07 '16 at 10:16
  • @123 OP asks for a way for a child process to set environment variables in the parent shell. I assume he want a general solution that also works when the child process is machine code, perl, python, ... Unless you can show me a way to source a python script, I will hold at this method. – Andreas Louv Jun 07 '16 at 10:19
  • What i meant is, I can't see a reason to use an external process to set variables in the current shell. You can run python et al. inside a sourced script and have them output the values you want anyway. – 123 Jun 07 '16 at 12:41
  • @123 And how should that Python program return the variables that should be added in the sourced shell...? – Andreas Louv Jun 07 '16 at 12:53
  • print/echo them. `IFS=$'\n' export vars=($(python -c 'print "1\n2 3\n4"'))` or don't export the array and assign the array elements to exported vars as needed in the sourced script. – 123 Jun 07 '16 at 13:18