There are two ways to get data from commands into a shell variable.


Backtics

Run the command with backtics. Typically this is used to read ONE line or ONE number.

d=`date`

u=`uptime`



While read

You can process each line of a multi line input like this:


ls -l / | grep Feb | while read perm number owner group size month date time filename

do

echo $filename was made in Febuary

done





Filtering

If the command has two much information, you can use the head, tail, grep and cut commands.


Head and tail filter whole lines by count.

The command 'head -5' gives you the first five lines of it's input.
sort < /etc/passwd | head -5
tells you the first five users in /etc/passwd in alpha order.


The command 'tail -7' gives you the last seven lines of it's input.
sort < /etc/passwd | tail -7
tells you the last 7 users in /etc/passwd in alpha order.


You can combine them like this:
sort < /etc/passwd | head -4 | tail -1
tells you the fourth person in alpha order from the file.


Grep filters whole lines by content.

cat < /etc/passwd | grep apoe
gives you all lines that contain apoe
cat < /etc/passwd | grep -v apoe
gives you all lines that do NOT contain apoe.



The cut command filters parts of lines.

cat < /etc/passwd | cut -c10-20
gives you the 10,11,12,13,14,15,16,17,18, and 19th character of each line of the file.


cat < /etc/passwd | cut -f4 -d":"
gives you the fourth field, where fields are delimited by colons.


day_of_week=`date | cut -f2 -d" "`
gives you the second field, where fields are delimited by spaces.