Reputation: 1272
I need to get all the wars on a remote tomcat server printed via my bash script. I am able to ssh on the remote server and execute the command to get wars with version :-
${SSH} ${DEST_USER}@${DESTHOST} "Command"
however if I am storing it in a variable I don't get any-thing:-
output=${SSH} ${DEST_USER}@${DESTHOST} "Command"
echo $output
Based on a bit research if I try it as
output=$(${SSH} ${DEST_USER}@${DESTHOST} "Command"
echo $output
I got my output stored (need to understand why?).
Secondly the output I got in a single line as:
abc_1.2.war ijk_2.2.war hij_3.2.war xyx_5.1.war
how can I format this output some thing like:
Name version
abc 1.2
ijk 2.2
hij 3.2
xyz 5.1
Upvotes: 2
Views: 8441
Reputation: 247082
Bash handles lines like this:
a=b c=d command
by temporarily setting environment variables "a" and "c" only for the duration of the command. They are not normal shell variables, and they won't exist after the command completes.
When you write
output=${SSH} ${DEST_USER}@${DESTHOST} "Command"
you are setting the "output" variable to the contents of "$SSH" for the duration of the "$DEST_USER@$DESTHOST" command (I'd expect you would receive a "command not found" error).
The way to capture the output of a command, as you have discovered, is with the $()
syntax
output=$($SSH $DEST_USER@$DESTHOST "Command")
(Note you don't always have to put braces around your variable names, that's only strictly necessary when you need to separate the variable name from surrounding text)
For your text formatting question:
output="abc_1.2.war ijk_2.2.war hij_3.2.war xyx_5.1.war"
{
echo Name version
for word in $output; do # no quotes around $output here!
IFS=_ read name version <<< "$word"
echo "$name" "${version%.*}"
done
} | column -t
Name version
abc 1.2
ijk 2.2
hij 3.2
xyx 5.1
Here I use braces to group the header and the lines from the for-loop together to send them to column. I don't assume you know all the file extensions, but I do assume each file has an extension. The "${version%.*}"
part removes the last dot and any following characters from the end of the value of the "version" variable.
Upvotes: 4
Reputation: 3154
I can't help with the 'why' right now. However you can produce the desired output from the variable(containing single line) as follows :
echo "Name version"
echo $output | grep -Eo "[a-zA-Z]+_[0-9]+.[0-9]+"| tr '_' ' '
Upvotes: 0