0

I am trying to debug a shell script executing on a remote server, where I do not have access to the standard output of the script. Can I redirect the output to go over a socket?

1 Answer 1

2

I was able to achieve this by redirecting output to a fifo, and using the fifo as the input for nc:

#/bin/sh -e

# create a fifo
unlink /tmp/f
mkfifo /tmp/f

# connect to the server in the background
nc localhost 4444 < /tmp/f &

# redirect stdout to the fifo
exec > /tmp/f

# an example that writes to stdout
while true; do
    sleep 1
    echo "hello world"
done

Note this is only transmitting stdout to the socket; you could add exec 2> /tmp/f to include stderr. I didn't succeed at getting stdin wired up but it should be possible.

(An earlier version of this script swapped nc with exec; this worked on Zsh, but not BusyBox's shell, ash.)

3
  • wouldn't just piping the command in question to nc do? i.e. while ...; done | nc .... Or put the actual work in a function and redirect that, dosmth() { while ...; done ; } and dosmth | nc ... Commented Dec 4, 2022 at 18:42
  • Note that [ 1 ] doesn't test the numerical value you put there but only checks if the string inside the brackets is non-empty. I.e. [ 0 ] and [ false ] are as true as [ 1 ] (but [ "" ] would be falsy). For an always-true condition, you could use while true; do... Commented Dec 4, 2022 at 18:45
  • 1
    Ok, switched to while true. My scenario involved an init script that I could modify, but I could not control how it was executed by the kernel. Commented Dec 4, 2022 at 19:33

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.