Store partial result of ssh command in array

115 Views Asked by At

Hi lets say I have the following servers:

  • server1:
  1. /root/script.sh
  • server2:
  1. root/folder1
  2. root/folder1/file1.log
  3. root/folder1/file2.log
  4. root/folder1/file3.log

When I call (from server1) script.sh I have the following which works okay and will print the list of files in folder 1:

server2="1245@server2"
    
array=(
    $(
        ssh $server2"
            ls folder1
        "
    )
)
    
if [ $? -eq 0 ]; then
    log "SUCCESSFULLY retrieved list of files from $server2. Proceed. . . "
else
    log "FAILED while retrieving files from $server2. Exit with error. . . "
    exit 1
fi

printf '%s\n' "${array[@]}"

Result of array:

file1.log
file2.log
file3.log

But, I what I want to do is the following:

  1. Execute script.sh from server1
  2. Open ssh connection to server2
  3. Check if directory folder1 exists
  4. If exists store list of files from folder1 to an array that will be later on used in script.sh
  5. Else store 0 in array
  6. Close ssh connection
  7. Check if previous ssh request was successful
  8. Print array
  9. Use array
server2="1245@server2"
    
array=(
    $(
        ssh $server2"
        
            #do something else
            #do other stuff
        
            if find folder1 -mindepth 1 -maxdepth 1 | read; then
                echo ""Directory folder1 is not empty and contains x files"" #dont store in array this echo
                #STORE ONLY THIS IN ARRAY - ONLY IN CASE DIR EXISTS AND NOT EMPTY
                ls folder1
            else
                echo 'Directory folder1 is empty'
            fi
            
            #do something else
            #do other stuff
        "
    )
)
    
if [ $? -eq 0 ]; then
    log "SUCCESSFULLY retrieved list of files from $server2. Proceed. . . "
else
    log "FAILED while retrieving files from $server2. Exit with error. . . "
    exit 1
fi

printf '%s\n' "${array[@]}"
1

There are 1 best solutions below

0
Eric Marceau On

Have you thought of directing the "report" (ls ?) you want to capture to stdout, and any other messaging of informational nature (echo) to stderr, the save the 2 streams to separate files ?