Here strings

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← here documentsHomeRedirection of standard error →

Here strings is just like here documents and syntax is:

command <<<$word

OR

command arg1 <<<"$word"

The $word (a shell variable) is expanded and supplied to the command on its standard input. The following wc command will count words from given argument:

wc -w <<< "This is a test."

Sample outputs:

4

grepping into a shell variable

Usually, you can not grep into a $var. For example, try to grep word "nor" using $var:

var="Neither in this world nor elsewhere is there any happiness in store for him who always doubts."
grep "nor" $var

Sample outputs:

grep: Neither: No such file or directory
grep: in: No such file or directory
grep: this: No such file or directory
grep: world: No such file or directory
grep: nor: No such file or directory
grep: elsewhere: No such file or directory
grep: is: No such file or directory

However, with here string you can grep into $var, enter:

grep "nor" <<<$var >/dev/null && echo "Found" || echo "Not found"

Sample output:

Found

Notice you can use shell pipes to grep into $var:

echo $var | grep -q "nor"  && echo "Found" || echo "Not found"

However, here strings looks more logical and easy to read.

Counting network interfaces

The following command counts the total active network interfaces:

wc -w <<<$(netstat -i | cut -d" " -f1 | egrep -v "^Kernel|Iface|lo")

Sample outputs:

3
← here documentsHomeRedirection of standard error →