Standard Input and Output Linux provides three I/O channels to Programs Standard input (STDIN) - keyboard by default Standard output (STDOUT) - terminal window by default Standard error (STDERR) - terminal window by default
Redirecting Output to a File STDOUT and STDERR can be redirected to files: command operator filename Supported operators include: > Redirect STDOUT to file 2> Redirect STDERR to file &> Redirect all output to file File contents are overwritten by default. >> appends.
Redirecting Output to a File Examples This command generates output and errors when run as non- root: $ ls –l f1.txt > f2.txt (only result is stored not error) Operators can be used to store output and errors: $ ls –l tot.txt 2> f3.txt(only error is stored not the result) $ ls –l tot.txt f1.txt &> f3.txt (concatenates the result and stores in f3.txt)
Redirecting STDOUT to a Program (Piping) Pipes (the | character) can connect commands: command1 | command2 Sends STDOUT of command1 to STDIN of command2 instead of the screen. STDERR is not forwarded across pipes Used to combine the functionality of multiple tools command1 | command2 | command3... etc
Redirecting STDOUT to a Program Examples less: View input one page at a time: $ ls -l /etc | less Input can be searched with / mail: Send input via $ echo "test " | mail -s "test" lpr : Send input to a printer $ echo "test print" | lpr $ echo "test print" | lpr -P printer_name
Combining Output and Errors Some operators affect both STDOUT and STDERR &>: Redirects all output: $ ls -l /etc -name passwd &> file1.txt 2>&1: Redirects STDERR to STDOUT Useful for sending all output through a pipe $ ls -l /etc -name passwd 2>&1 | less (): Combines STDOUTs of multiple programs $ ( cal 2007 ; cal 2008 ) | less
Redirecting to Multiple Targets (tee) $ command1 | tee filename | command2 Stores STDOUT of command1 in filename, then pipes to command2 Uses: Troubleshooting complex pipelines Simultaneous viewing and logging of output
Redirecting STDIN from a File Redirect standard input with < Some commands can accept data redirected to STDIN from a file: $ tr 'A-Z' 'a-z' < file1.txt This command will translate the uppercase characters in file1.txt to lowercase Equivalent to: $ cat file1.txt | tr 'A-Z' 'a-z'
Scripting: for loops Performs actions on each member of a set of values Example: for NAME in joe jane julie do MESSAGE='Projects are due today!' echo $MESSAGE | mail -s Reminder $ADDRESS done Can also use command-output and file lists: for num in $(seq 1 10) Assigns 1-10 to $num seq X Y prints the numbers X through Y for file in *.txt Assigns names of text files to $file