|


| NAVIGATION |
|
Home |
|
Store |
|
|
| INSIDE MAC |
|
Television Shows |
|
Broadcast Shows |
|
Daily News Shows |
|
Special Shows |
|
|
| EVENTS |
|
|
|
|
|
|
|
|
| DAILY TIPS |
|
Design |
|
Mac OS X |
|
Mac OS X UNIX |
|
|
| COMMUNITY |
|
Surveys |
|
|
| NEWS |
|
Current |
|
Press |
|
Archive |
|
|
| FEATURES |
|
Editorial |
|
Dr. Mac |
|
Reviews |
|
Reader Reports |
|
|
| RESOURCES |
|
FAQ |
|
Documentation |
|
Learning Center |
|
MAN pages |
|
Glossary |
|
Tutorials |
|
Tips |
|
Links |
|
|
|

|
|
|
OSXFAQ Mac OS X UNIX Tip-of-the-Day
Redirection - Redirect to a Variable
It's often useful to capture the output of a command into a shell variable. For example, this command returns the device identifier of the device mounted at '/Volumes/pw'
$ df | awk '/\/Volumes\/pw/ {print $1}'
/dev/disk3s2
$
We capture the output from this command into a shell variable called 'device' by typing:
$ device="$(df | awk '/\/Volumes\/pw/ {print $1}')"
$ echo $device
/dev/disk3s2
$
(We might use $device in a 'mount' command later in the script.)
However, only standard out is captured, as shown in this next example where we form an invalid 'awk' command.
$ device="$(df | awk '/\/Volumes\/pw {print $1}')"
awk: non-terminated regular expression \/Volumes\... at source line 1
context is
>>> <<<
$ echo $device
$
To capture standard error too, we simply merge it with standard out using the syntax '2>&1'.
$ device="$(df | awk '/\/Volumes\/pw {print $1}' 2>&1)"
$ echo $device
awk: non-terminated regular expression \/Volumes\... at source line 1 context is >>> <<<
$
Note that other shells such as 'sh' and 'tcsh' use a different syntax for command substitution - `command` instead of $(command):
$ device="`df | awk '/\/Volumes\/pw/ {print $1}'`"
|


|
Copyright © 2000-2010 Inside Mac Media, Inc. All rights reserved. |
Apple assumes no responsibility with regard to the selection, performance, or use of the products or services. All understandings, agreements, or warranties, if any, take place directly between the vendors and prospective users. |
| Apple, the Apple logo, Mac, PowerMac G4, PowerMac G5, Xserve, Xserve RAID, PowerBook, iBook, Airport, AirPort Extreme, iMac, eMac, iLife, iMovie, iCal, iPhoto, iTunes, QuickTime, FireWire, iPod, iSight, AppleWorks, Macintosh, Jaguar, Panther, Mac OS, Mac OS X and Mac OS X Server are trademarks of Apple Computer, Inc. |
|