Skip to content

Instantly share code, notes, and snippets.

@uryossa
Created June 7, 2024 09:00
Show Gist options
  • Save uryossa/dd3a262b4b6ee29408f4528c076ed397 to your computer and use it in GitHub Desktop.
Save uryossa/dd3a262b4b6ee29408f4528c076ed397 to your computer and use it in GitHub Desktop.
#!/bin/bash
# This script executes a remote command over SSH, captures its standard output and error output,
# and returns the results along with the exit status of the command.
# Execute from another script and return variables
# Usage: source <(./ssh_exec.sh <ssh_options> <remote_command>)
# Then access the variables:
# $SSHSTATUS
# $RETURNSTATUS
# $RETURNSTDOUT
# $RETURNERROUT
# Define the usage function
usage() {
echo "Usage: $0 <ssh_options> <remote_command>"
echo "Note: The remote command must be enclosed in single or double quotes."
exit 1
}
# Check the arguments
if [ "$#" -lt 2 ]; then
usage
fi
# Separate SSH options and the remote command
REMOTE_COMMAND="${!#}"
SSH_OPTIONS=("${@:1:$#-1}")
# Debug: Check SSH options and remote command
# echo "SSH_OPTIONS: ${SSH_OPTIONS[@]}"
# echo "REMOTE_COMMAND: $REMOTE_COMMAND"
# Execute the SSH command and capture the output
OUTPUT=$(ssh "${SSH_OPTIONS[@]}" "bash -c \"
{
{
$REMOTE_COMMAND
echo __RET=\\\$?
} 2> >(awk '{print \\\"__STDERR__\\\" \\\$0}') | awk '{print \\\"__STDOUT__\\\" \\\$0}'
}\" 2>&1")
SSHSTATUS=$?
# Debug: Check the output of the SSH command
# echo "OUTPUT: $OUTPUT"
# Parse the remote command's exit status
RETURNSTATUS=$(echo "$OUTPUT" | grep "^__STDOUT____RET=" | sed 's/^__STDOUT____RET=//')
# Parse standard output and error output
RETURNSTDOUT=$(echo "$OUTPUT" | grep -v -E "^__STDOUT____STDERR__|^__STDOUT____RET=" | grep "^__STDOUT__" | sed 's/^__STDOUT__//')
RETURNERROUT=$(echo "$OUTPUT" | grep "^__STDOUT____STDERR__" | sed 's/^__STDOUT____STDERR__//')
# Output variables (for debug purposes)
# echo "SSHSTATUS: $SSHSTATUS"
# echo "RETURNSTATUS: $RETURNSTATUS"
# echo -e "RETURNSTDOUT:\n$RETURNSTDOUT"
# echo -e "RETURNERROUT:\n$RETURNERROUT"
echo SSHSTATUS=$SSHSTATUS
echo RETURNSTATUS=$RETURNSTATUS
echo -n RETURNSTDOUT='"'
echo -n "$RETURNSTDOUT"
echo '"'
echo -n RETURNERROUT='"'
echo -n "$RETURNERROUT"
echo '"'
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment