unix - How can I take the output of a shell script and place it in a file on the command line?
2014-04
How can I take the output of a shell script and place it in a file on the command line?
# write to file
sh myscript > out.txt
# append to file
sh myscript >> out.txt
# write both output and stderr to file
sh myscript 2&1>> out.txt
$ ./foo >> myoutputfile.txt
Let's say I have a command called foo
which prints a number to the screen when called:
$ foo
3
Let's also say I have another command called bar
which prints another number to the screen when called:
$ bar
5
I'm looking to write a shell script which will arithmetically add together the output of foo
and bar
(3+5=8). How would I do that? (The outputs from the commands are not known ahead of time. They just so happen to have been 3 and 5 the last time they were run. They could have been something else.)
Use bash's let
to evalutate arithmetric expressions.
#!/bin/bash
a=`echo 3`
b=`echo 5`
let c=$a+$b
echo $c
Just substitute the calls to echo
with your program calls.
An alternative to let
is to use double-parenthesis syntax:
(( c = $(foo) + $(bar) ))
or
echo $(( $(foo) + $(bar) ))
or using variables, you can omit the dollar sign on the right hand side of the equals:
(( c += $(foo) + num ))
(which also illustrates an incremental assignment)
If you're using non-integers you can use bc
:
echo "$(foo) + $(bar)" | bc
or
c=$(echo "$(foo) + $(bar)" | bc)
One advantage of using double parentheses is that you can put spaces around the operands and operators to make things more readable:
(( c = ( a + b ) * ( i - j ) ))
bash:
bc < <({ foo ; echo + ; bar ; } | tr '\n' ' ' ; echo)
If the output is integers only:
$(( $(foo) + $(bar) ))