1

How to execute the local bash script file with the references on the remote server using ssh?

a.sh

#!/bin/bash

echo A
source b.sh

b.sh

#!/bin/bash

echo B

Executing on the remote ssh server:

cat a.sh | ssh myserver

A
-bash: line 4: b.sh: No such file or directory

What are the options for solving this issue without copying files to the remote server?

Jonas
  • 4,683
  • 4
  • 45
  • 81

2 Answers2

1

As long as you only have references with one level of depth, you can use awk to directly insert the contents of the referenced file into the first one.

$ awk '/^source/{while((getline line < $2) > 0){print line}close($2);next}1' a.sh

This outputs:

#!/usr/bin/bash

echo A
#!/usr/bin/bash

echo B

So you could use it like this:

$ awk '/^source/{while((getline line < $2) > 0){print line}close($2);next} +1' a.sh | ssh myserver

If you wanted to use dependencies with more depth, you could apply this same command in a loop until the result file didn't change.

Miguel
  • 2,130
  • 1
  • 11
  • 26
  • If the file is not ending with the two new lines, then the last line is repeated twice. There is not enough of my awk voodoo skill to fix that. Please help :) – Jonas May 13 '21 at 07:23
  • OK, now it should work correctly. Let me know :D – Miguel May 13 '21 at 09:36
0

Using @miguel answer wrote this script that might be helpful to someone who needs to execute scripts on the remote ssh servers.

inline.sh

#!/bin/bash

# Hardcoded 4 nesting levels
awk '/^source/{while((getline line < $2) > 0){print line}close($2);next} +1' < $1 | \
awk '/^source/{while((getline line < $2) > 0){print line}close($2);next} +1' | \
awk '/^source/{while((getline line < $2) > 0){print line}close($2);next} +1' | \
awk '/^source/{while((getline line < $2) > 0){print line}close($2);next} +1' 

Uasage:

$ inline.sh myscript.sh | ssh -A myserver -C "MYVAR=myval bash"
Jonas
  • 4,683
  • 4
  • 45
  • 81
  • That's atrocious. Use a loop until there are no more `source` commands to inline. (Also, lose the [useless `cat`](https://stackoverflow.com/questions/11710552/useless-use-of-cat).) – tripleee May 13 '21 at 12:06
  • Mea culpa! Probably I am born too late to write bash loops. Can't say I didn't try. – Jonas May 13 '21 at 12:16