0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use Here String in Bash: Syntax and Examples

In Bash, a here string uses the syntax <<< "string" to pass a string as input to a command. It is a simple way to feed a single string to commands that read from standard input.
📐

Syntax

The basic syntax of a here string in Bash is:

command <<< "string"

Here:

  • command is any command that reads input from standard input.
  • <<< is the here string operator.
  • "string" is the string you want to pass as input.

This sends the string as if it were typed into the command's input.

bash
cat <<< "Hello, Bash here string!"
Output
Hello, Bash here string!
💻

Example

This example shows how to use a here string to pass a string to the grep command to search for a word:

bash
grep "world" <<< "Hello world from here string"
Output
Hello world from here string
⚠️

Common Pitfalls

Common mistakes when using here strings include:

  • Forgetting to quote the string, which can cause word splitting or globbing.
  • Using here strings with commands that expect multiple lines of input, where a here document might be better.
  • Confusing here strings (<<<) with here documents (<<).
bash
echo <<< Hello world  # Wrong: no quotes, splits words

echo <<< "Hello world"  # Correct: quotes preserve string
Output
Hello world
📊

Quick Reference

Here is a quick summary of here string usage:

  • <<< "string" sends string as input to a command.
  • Use quotes to preserve spaces and special characters.
  • Best for short, single-string input.
  • For multiline input, use here documents (<<).

Key Takeaways

Use <<< "string" to pass a string as input to a command in Bash.
Always quote the string to avoid word splitting and globbing issues.
Here strings are ideal for short, single-line input to commands.
For multiline input, prefer here documents (<<) instead.
Here strings simplify feeding input without creating temporary files or echo pipelines.