Open In App

Shell Scripting – Here Strings

Last Updated : 01 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Here String is a kind of string that is used for input redirection from text or a variable. In here string Input will be mentioned in the same line within the quotes. the string inside the quotes is known as the Here string and Its command contains “<<<” (3 less than the symbol). Here string and a heredoc are extremely similar, but the former is a lot more simplified version of the latter.
Because of this, a delimiter token is not required in this text. Whenever we need a quick technique to transform some strings into a command, it is typically preferred. It is also known as an ordinary string which is used for the purpose of input redirection, It’s not a special kind of string. The execution contains only a few steps.

Basic Syntax:

To construct a here-string, we use the “<<<” operator to redirect a string into a command. Concretely, the syntax is:

$ command <<< $DATA

What it essentially does is expand the variable DATA and redirect the output string to the COMMAND.

Usage of Here Strings

For input redirection from text or a variable, the here-string is utilized. On the same line, input is mentioned in single quotations (“).

Example 1: Basic Usage

#!/bin/bash
wc -w <<< 'Hello GeeksforGeeks\n'

 In this example, the string It is “Hello GeeksforGeeks\n” is called the here-string.

 

Output:

2

There are 2 words, so the output is been retrieved as 2.

Example 2: String with more words

#!/bin/bash
wc -w <<< 'Welcome to GFG a helping platform for CS Students'

In this example, the string “Welcome to GFG a helping platform for CS Students” is called the here-string.

 

Output:

9

There are 9 words, so the output is been retrieved as 9.

Example 3: Here String with Parameter

if grep -q "txt" <<< "$VAR"
then 
echo "$VAR contains the substring sequence \"txt\""
fi

 

In the above example, the here-string is present with a parameter $VAR which is working as a parameter.

Example 4: Escape Special Characters in Here String

word=$'HELLO\ngfg'
echo "$WORD"

It’s a kind of special character which is sometimes used in the here-string

 

The above example is here-string with Escape Special Characters and it’s Escaping some characters.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads