You know how to save output in a file with >. To save output in a variable, use $( ):
text
learner@tidepool:~$ ERRORS=$(grep -c ERROR ~/logs/till.log)
learner@tidepool:~$ echo "errors today: $ERRORS"
errors today: 2ERRORS=$(grep -c ERROR till.log)you type
ERRORS=2grep writes 2
This is the same idea as variables and wildcards: the shell changes the line first, then runs it.
Use it anywhere in a line
$( ) works in any argument, also inside double quotes:
text
learner@tidepool:~$ echo "report made by $(whoami) on $(date +%A)"
report made by learner on Mondaydate +%A writes the name of the day. +%A tells date what to write. date --help lists the other codes.
A number alone
Use wc -l < FILE, so that only the number goes into the variable, with no file name:
text
learner@tidepool:~$ COUNT=$(wc -l < ~/orders.txt)
learner@tidepool:~$ echo "orders: $COUNT"
orders: 12