Leo
Leo

Reputation: 189

Assign list of outputs from command executed remotely via ssh to a variable in shell

I am trying to connect to a Linux server and execute some commands. Below is the code snippet for it and the output. I want to assign the output of 'ls' to a variable so that i can process it further. Let me know how to do it?

USERNAME=root
PASSWD=abc
HOST=1.2.3.4
SCRIPT="cd /tmp/sample/; ls"
cmd="ssh -l $USERNAME $HOST $SCRIPT"
$cmd

Output: list the directories as below.

5
6
7
10
12

Upvotes: 0

Views: 1281

Answers (2)

konsolebox
konsolebox

Reputation: 75548

This isn't neat for me:

SCRIPT="cd /tmp/sample/; ls"
cmd="ssh -l $USERNAME $HOST $SCRIPT"

Mixing local and remote commands like that could sometimes lead to misinterpretation.

If you could use bash, the better way to do it is to use arrays:

SCRIPT="cd /tmp/sample/; ls"
CMD=(ssh -l "$USERNAME" "$HOST" "$SCRIPT")
OUTPUT=$("${CMD[@]}")
echo "$OUTPUT"

If you like you could save the output as an array of lines instead:

SCRIPT="cd /tmp/sample/; ls"
CMD=(ssh -l "$USERNAME" "$HOST" "$SCRIPT")
readarray -t OUTPUT < <("${CMD[@]}")
for A in "${OUTPUT[@]}"; do
    echo "$A"
done

Additional note: ls is wise enough to detect if it has to populate files line by line or not depending on the output but some versions of it are not. If that's the case add the option -1 to it.

Upvotes: 1

iruvar
iruvar

Reputation: 23374

You shouldn't be parsing ls output

If you really need to do this process substitution with bash is one option. Note that the solution below does not store ls output in a single variable, it processes the output line by line

#!/usr/bin/env bash
USERNAME=******
PASSWD=********
HOST=127.0.0.1
SCRIPT="cd /tmp/; ls"
cmd="ssh -l $USERNAME $HOST $SCRIPT"
while IFS= read -r line 
do
    echo "$line"
done<  <($cmd)

Upvotes: 1

Related Questions