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
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.)
-
wouldn't just piping the command in question to
ncdo? i.e.while ...; done | nc .... Or put the actual work in a function and redirect that,dosmth() { while ...; done ; }anddosmth | nc ...ilkkachu– ilkkachu2022-12-04 18:42:55 +00:00Commented 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 usewhile true; do...ilkkachu– ilkkachu2022-12-04 18:45:49 +00:00Commented Dec 4, 2022 at 18:45 -
1Ok, 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.rgov– rgov2022-12-04 19:33:10 +00:00Commented Dec 4, 2022 at 19:33