2

Hoi, is it possible to run "source ./.bash_file" via node? Try to create a small tool to create ssh-alias with electron-app, but cant update the bash-file to make new aliases available for terminal.

Thanks

fpvz
  • 93
  • 9

1 Answers1

4

Yes, you can source a bash script using either child_process.spawn() or child_process.exec().

BUT it will not work as I believe you expect.

This is because that, while spawn creates a new process, it also starts a new shell in that process in which your script will be sourced and after which will be killed when the newly spawned process ends.

If you only need the result of the script available in the context of the newly spawned shell, you can create a new script that first sources your bash_file and then uses any changes made to the currently running shell elsewhere in the same script.

Assume:

bash_script.sh contains

#!/bin/bash
export FOO=1 # exports new FOO variable into currently running shell

and test_bash_script.sh contains

#!/bin/bash
source ./bash_script
echo $FOO

and in the current shell, you

$ chmod +x test_bash_script.sh

then

$ test_bash_script.sh      # => will echo '1' to stdout
$ echo $FOO                # => echoes nothing

The second line doesn't echo anything because FOO is only available in both bash_script.sh and test_bash_script.sh.

Rob Raisch
  • 17,040
  • 4
  • 48
  • 58