Feeding Input: <, Here-Documents and Here-Strings

Input from a file: <

Many commands read standard input when you don't give them a file name. Normally that is the keyboard. < connects a file to it instead:

wc -l names.txt
wc -l < names.txt

In the terminal

student@vulntech:~$ wc -l names.txt
9 names.txt
student@vulntech:~$ wc -l < names.txt
9

See the difference? Given a file name, wc prints the name too. With < it only receives the content, which is handy when you just want the number.

Here-documents: several lines of input

A here-document feeds the lines you type into a command, up to an end marker you choose (EOF is the usual one). After the first line, bash shows a > prompt until you type the marker on a line of its own:

cat <<EOF
First line
Second line
EOF

In the terminal

student@vulntech:~$ cat <<EOF
> First line
> Second line
> EOF
First line
Second line

Add > and you create a file with several lines in one go. Installation guides often write configuration files this way:

cat <<EOF > crew.txt
Captain: Ada
Cook: Bo
Lookout: Cy
EOF
cat crew.txt

In the terminal

student@vulntech:~$ cat <<EOF > crew.txt
> Captain: Ada
> Cook: Bo
> Lookout: Cy
> EOF
student@vulntech:~$ cat crew.txt
Captain: Ada
Cook: Bo
Lookout: Cy

Inside a here-document, variables such as $USER and commands in $( ) are filled in. Put the marker in quotes ('EOF') to keep the text exactly as typed:

cat <<EOF
Hello $USER, your home is $HOME
EOF
cat <<'EOF'
Hello $USER, your home is $HOME
EOF

In the terminal

student@vulntech:~$ cat <<EOF
> Hello $USER, your home is $HOME
> EOF
Hello student, your home is /home/student
student@vulntech:~$ cat <<'EOF'
> Hello $USER, your home is $HOME
> EOF
Hello $USER, your home is $HOME

Here-strings: one line of input

<<< passes a single string as input, so you don't need a file to try something. (tr a-z A-Z turns small letters into capitals; more about tr in the next module.)

tr a-z A-Z <<< "make me loud"
wc -w <<< "how many words are in here"

In the terminal

student@vulntech:~$ tr a-z A-Z <<< "make me loud"
MAKE ME LOUD
student@vulntech:~$ wc -w <<< "how many words are in here"
6
You typeThe command reads
command < fileThe contents of file
command <<EOF ... EOFThe lines you type, up to EOF
command <<< "text"Just that text

Remember: < reads a file, <<EOF reads the lines you type until EOF, <<< reads one string.

HOME LEARN COMMUNITY DASHBOARD
Practice terminal Starting…