Is there a way to do a remote "source" of a bash script file to set variable ?

Solution Verified - Updated -

Environment

  • Red Hat Enterprise Linux 5
  • bash-3.2-xx.el5

Issue

  • Trying to do a "remote sourcing" to set some variables locally (in a bash script) from a remote server.
  • The remote server generate, every 30 minutes, a little bash script which only contains vars.
  • From workstation, need to source this file to gets all data from all vars. But the following solution doesn't work on Red Hat Enterprise Linux 5.

    [user1@workstation ~]$ ssh user1@server cat /test
    upt="just a test"
    [user1@workstation ~]$ cat <(ssh user1@server cat /test)
    upt="just a test"
    [user1@workstation ~]$ source <(ssh user1@server cat /test)
    [user1@workstation ~]$ echo $upt
    <--- Variable is not set
    [user1@workstation ~]$

  • The above solution is working on Fedora 11 and RHEL6, but is not working in RHEL5 ?

Resolution

  • 'eval' command can be used instead of 'source' with a subshell . 'eval' is really the better choice for this situation including on Fedora 11 and RHEL 6.
[user1@workstation ~]$ ssh user1@server cat /test
upt="just a test"

[user1@workstation ~]$ cat <(ssh user1@server cat /test)
upt="just a test"

[user1@workstation ~]$ eval $(ssh user1@server cat /test)
[user1@workstation ~]$ echo $upt 
just a test

Diagnostic Steps

  • Going through the 'man' pages of 'source' command [man source] , observe that 'source' command takes/expect only *filename* as arguments.
source filename [arguments]  

Read and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename.The return status is the status of the last command exited within the script (0 if no commands are executed), and false if filename is not found or cannot be read.  

With that, the command redirection which mentioned above may not work. But the confusing point here is ,
  • It's true that "source" wait for a file... But, "cat" also wait for a file... and it work with this command :
    cat <(ssh root@server cat /tst)

  • It looks something is changed in upstream bash versions that makes redirection possible or we are hitting a bug in RHEL5 that prevents redirection.

This solution is part of Red Hat’s fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form.

Comments