In Bash, the <<< symbol is used for “here strings.” It allows users to pass a string as standard input to a command, similar to the pipe symbol (|) that passes the output of one command as input to another. However, instead of sending the output of a command, the <<< operator sends a string.
This guide will illustrate the meaning of the “<<<” operator with the practical implementation in Bash.
- How to Use “<<<” in Bash?
- Pass the String as Input
- Search for the Specific Word
- Count the Line Numbers in a String
- Send the File Content to a Command
How to Use “<<<” in Bash?
When users use the <<< operator, Bash sends the string as the input to the command. The syntax for using the <<< operator is as below:
$ command <<< string
In the above syntax, the “command” is the command that users want to run, and the “string” is the string users want to pass as input.
Example 1: Pass the String as Input
An example is considered to send the specific string to the “cat” command via the “<<<” operator. The <<< operator tells Bash to pass the string ‘hi there’ as input to the cat command:
$ cat <<< 'hi there'
The output shows that ‘hi there’ has been passed to the “cat” command and displayed in the terminal.
Example 2: Search for the Specific Word
A string “Hello World” is carried out and pass it as input to the “grep” command to search for the word “World“:
$ grep "World" <<< "Hello World"
The output of the above execution is “Hello World” because that is the string that contains the word “World.”
Example 3: Count the Line Numbers in a String
For counting the line numbers in a string, use the “wc” command. Here, the <<< operator sends the string as the input to the wc command, and the -l option tells wc to count the number of lines in the input string as below:
$ wc -l <<< "This is a string with multiple lines. This is the second line. And this is the third."
The output of this command indicates three lines in the input string.
Bonus Tip: Send the File Contents to a Command
If users want to send the contents of a file as input to a command, use the < operator instead of “<<<” as below:
$ cat < file.txt
It sends the contents of the file file.txt as input to the “cat” command and displays it in the terminal.
In Bash, the “<<<” operator means “here strings”. It allows users to pass a string as the input to a command. This operator allows users to search for a specific word, count the line numbers in a string, and many more.
This guide has explained the meaning of the “<<<” operator with the practical implementation.