What if we don’t want the output of a command to go to the screen but to a file? Or get the input to a command from a file instead of the keyboard?
Redirection allows us to change where a command gets input or sends output.
>
- redirect output to a new file
>>
- redirect output to an existing file and append to the end
<
- redirects the input to a file (instead of the keyboard)
|
- sends the output of one program to another program
% echo "hello there, children" hello there, children % echo "hello there, children" > chef % ls chef % cat chef hello there, children % echo "hey chef" >> chef % cat chef hello there, children hey chef % date Sun Dec 22 02:11:56 MST 2024 % date >chef % cat chef Sun Dec 22 02:11:56 MST 2024
echo
to put text into a file.
% cp ~/monster . % ls monster % ls >file_list % ls file_list monster % cat file_list file_list monster % pwd >> file_list % cat file_list file_list monster /tmp/PmWiki.tmp
echo
isn’t the only command whose output we can redirect.
% cp ~/monster . % ls -l >tempfile % cat <tempfile total 4 -rw------- 1 cs155 class 401 Dec 22 02:11 monster -rw------- 1 cs155 class 0 Dec 22 02:11 tempfile % cat tempfile total 4 -rw------- 1 cs155 class 401 Dec 22 02:11 monster -rw------- 1 cs155 class 0 Dec 22 02:11 tempfile
Many commands accept input from a file or a command line argument.
% ls -l > tempfile % more tempfile ... % rm tempfile % ls -l | more ... %
This is useful for combining operations without making temporary files
ls -l | more
for listing a directory with many files
man cat | more
to learn about the cat
command
man
or info
more
or cat
cp
, mv
, rm
, mkdir
, rmdir
echo
"
>
, >>
, |
<