Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

You know when you do something like apt-cache search something | less? Well (in a Bash script) how do you get the input and set it to a variable (like less is doing, but less isn't a Bash script)?

share|improve this question
So you want to define a variable containing the output of a command in a Bash script? – cYrus Aug 24 '10 at 19:59
up vote 1 down vote accepted

If you want to do something like what less is doing (receive input on its standard input, process it, then output it) in a script that you write, you can use a while read loop in your script.

echo "Beginning"
while read -r line
    echo "Processed: [$line]"
echo "Ending"

Then you can run it like this:

some_command | your_script

and your output will look like this:

Processed: [First line of input]
Processed: [Second line of input]
Processed: [Third line of input]
Processed: [Fourth line of input]

Assuming that some_command by itself outputs:

First line of input
Second line of input
Third line of input
Fourth line of input

The variable $line is being assigned the value of each line of input in turn. You could accumulate those lines if you needed to by concatenating each line onto a scalar variable:




or by appending elements on the end of an array:

share|improve this answer

You are misunderstanding command | less. In that scenario, the less command doesn't cause the connection; the pipe connects the previous command to less. Also, you're saying 'input' where I think you mean 'output'. What you type into the terminal is the input in this case; the output is whatever command spits back out. less receives the output of the command via | (aka, the pipe). The pipe takes the standard output of one command and plugs it in as the standard input of another. (You might find this Wikipedia article helpful as a start.)

To assign the output of one command to a variable, you would normally do something like this:

# older syntax for above

But I very much doubt you really want to assign the output of apt-cache search foo to a variable.

Can you elaborate a bit on your larger goal? What are you really trying to do?

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .