1

Is it possible to output the result of a command to a file AND set a variable, all in the same command?

The following will append the output to a file, but wont set var.

for i in myarray; do
    var=$(command >> file)
done

Not sure if this is possible or not.

1 Answer 1

5

The following will send the output to file as well as set var:

var=$(command | tee -a file)

This works because tee duplicates the output of command. One copy is appended to file while the other copy is sent to stdout. Command substitution, $(...), captures that stdout and saves it in var.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.