Bash < and > usage
Bash uses < and > for some special behavior that when you get the hang of it you love them.
Input redirection
< or input redirection
So you don’t want to keep writing every single time the input for a command?
command input1 input2 input3 ...
You are lucky because < will save you some time
command < inputs.txt
With this you pass the input with a file and not with the keyboard
<< or here document
You can give multiple lines to a command and is going to be read as a document, it will also remove tabs before the text
command <<EOF
line1
line2
EOF
You can also don’t allow variables in this “file”
command <<'EOF'
line1
${variable}
EOF
Here the string ${variable} will be used and not the variable value, also tabs will not be ignored, if you want to ignore them you can use <<-
* You can change EOF for whatever delimiter you like
<<< or here string
You pass a string to a command that reads from stdin
for file in *.mp4; do
duration=$(<long_command>)
IFS=':' read -r hours minutes seconds <<< $duration
...
done
Output redirection
> and >>
You need to have the output of a command written into a file?, you can use > or >>. Both of these commands will create the file if did not exist but if it exists then the first command will wipe the content of the file and write, on the other hand >> will append the data to the file
command > out.txt
command >> out.txt
M>&N and M>N
With M>&N you can redirect the file descriptor M (default 1, or stdout) to N. You can use it, for example, to redirect stderr to stdout.
command input1 2>&1
You can also remove & and this will redirect that file descriptor to a file
command input 2>err.txt 1>out.txt
A special case of this is &>"filename", with this you are redirecting stdout and stderr to a file named filename.
You can combine them
You don’t have to use only one of the command described in this page, you can use multiple if required
command < input.txt > out.txt
You want to read more? https://tldp.org/LDP/abs/html/io-redirection.html https://tldp.org/LDP/abs/html/x17837.html (Here string)