0
0
Bash Scriptingscripting~5 mins

Here strings (<<<) in Bash Scripting

Choose your learning style9 modes available
Introduction
Here strings let you send a small piece of text as input to a command easily, without creating a file.
You want to quickly provide input to a command that reads from standard input.
You need to test a command with a short string without typing it interactively.
You want to avoid creating temporary files for simple input data.
You want to pass a variable's content as input to a command.
You want to simplify scripts by embedding input directly.
Syntax
Bash Scripting
command <<< "string"
The string after <<< is sent as input to the command's standard input.
The string can be quoted or unquoted, but quoting preserves spaces and special characters.
Examples
Counts the number of words in the string 'hello world'.
Bash Scripting
wc -w <<< "hello world"
Searches for the word 'apple' in the given string.
Bash Scripting
grep 'apple' <<< "apple banana cherry"
Reads the string into a variable and prints it.
Bash Scripting
read line <<< "This is a line"; echo "$line"
Sample Program
This script counts words in a string and searches for the word 'cat' in another string using here strings.
Bash Scripting
#!/bin/bash

# Count words in a string using here string
word_count=$(wc -w <<< "one two three four")
echo "Word count: $word_count"

# Search for a word in a string
if grep -q 'cat' <<< "dog cat mouse"; then
  echo "Found cat"
else
  echo "Cat not found"
fi
OutputSuccess
Important Notes
Here strings add a newline at the end of the string automatically.
They are useful for short inputs; for longer inputs, consider here documents or files.
Not all shells support here strings; bash and zsh do.
Summary
Here strings (<<<) send a short string as input to a command.
They simplify passing data without files or interactive typing.
Useful for quick tests and simple scripts.