LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   save command output to variable (https://www.linuxquestions.org/questions/programming-9/save-command-output-to-variable-4175445981/)

rajachan 01-17-2013 02:03 AM

save command output to variable
 
hi

how to store below command output in variable in ksh. i had 3 columns of output.

echo $line|sed '/^$/d' |sed '/,/d'|sed '/SQL/d'|sed '/-/d'|sed '/NAME/d'| cut -d " " -f1)
echo $line|sed '/^$/d' |sed '/,/d'|sed '/SQL/d'|sed '/-/d'|sed '/NAME/d'| cut -d " " -f2
echo $line|sed '/^$/d' |sed '/,/d'|sed '/SQL/d'|sed '/-/d'|sed '/NAME/d'| cut -d " " -f3

colucix 01-17-2013 02:11 AM

Use command substitution, e.g.
Code:

var=$(command)
This syntax is preferred over the old one using backticks
Code:

var=`command`
but sometimes you require it for compatibility reasons with the old Bourne shell /bin/sh.

rajachan 01-17-2013 02:41 AM

Quote:

Originally Posted by colucix (Post 4871959)
Use command substitution, e.g.
Code:

var=$(command)
This syntax is preferred over the old one using backticks
Code:

var=`command`
but sometimes you require it for compatibility reasons with the old Bourne shell /bin/sh.

i tried using var.. but the output of $var is empty..

but actually i got output for the commands

kooru 01-17-2013 03:30 AM

An example, if can be useful:

Code:

$> test=$(echo "are we aliens?" | awk '{print $3}')
$> echo $test
$> aliens?


David the H. 01-18-2013 07:48 AM

Please use ***[code][/code]*** tags around your code and data, to preserve the original formatting and to improve readability. Do not use quote tags, bolding, colors, "start/end" lines, or other creative techniques.


Please show us the contents of the "$line" variable, the exact commands you're using, and the output/error messages you're getting. We can't see your screen, so we have no idea what you're doing wrong.

Some more context on what you are trying to do would help too. Where is this input coming from, and what do you really need to do with it?

In short, give us more details. It may be that there are better ways to do what you want.


Those long chains of separate seds are rather ugly in any case. You should be able to easily condense them into fewer ones. In fact, we could probably just do something like this:

Code:

read var1 var2 var3 _ <<<"$( sed -r '/(^$|[,-]|SQL|NAME)/d' <<<"$line" )"
Note that the above assumes there's always only a single line of text left after all the (d)eletes, and that that line will have at least 3 fields (anything extra will go into the throw-away _ variable.

It's also possible that awk is a better choice, since it's field-based. Or one of the shell's built in string manipulations. But again, we need to see what the input looks like before saying for sure.


All times are GMT -5. The time now is 09:06 AM.