What does the Bash operator <<< (i.e. triple less than sign) mean?

31.7k views Asked by At

What does the triple-less-than-sign bash operator, <<<, mean, as inside the following code block?

LINE="7.6.5.4"
IFS=. read -a ARRAY <<< "$LINE"
echo "$IFS"
echo "${ARRAY[@]}"

Also, why does $IFS remain to be a space, not a period?

4

There are 4 answers

5
Ignacio Vazquez-Abrams On BEST ANSWER

It redirects the string to stdin of the command.

Variables assigned directly before the command in this way only take effect for the command process; the shell remains untouched.

1
Barton Chittenden On

The reason that IFS is not being set is that bash isn't seeing that as a separate command... you need to put a line feed or a semicolon after the command in order to terminate it:

$ cat /tmp/ifs.sh
LINE="7.6.5.4"
IFS='.'  read -a ARRAY <<< "$LINE"
echo "$IFS"
echo "${ARRAY[@]}"

$ bash /tmp/ifs.sh 


7 6 5 4

but

$ cat /tmp/ifs.sh 
LINE="7.6.5.4"
IFS='.';  read -a ARRAY <<< "$LINE"
echo "$IFS"
echo "${ARRAY[@]}"

$ bash /tmp/ifs.sh 
.
7 6 5 4

I'm not sure why doing it the first way wasn't a syntax error though.

1
ryanbraganza On

From man bash

Here Strings A variant of here documents, the format is:

     <<<word

The word is expanded and supplied to the command on its standard input.

The . on the IFS line is equivalent to source in bash.

Update: More from man bash (Thanks gsklee, sehe)

IFS The Internal Field Separator that is used for word splitting after expansion and to split lines into words with the read builtin command. The default value is "<space><tab><new‐line>".

yet more from man bash

The environment for any simple command or function may be augmented temporarily by prefixing it with parameter assignments, as described above in PARAMETERS. These assignment statements affect only the environment seen by that command.

0
Ciro Santilli OurBigBook.com On

Just to provide a cleaner example of <<< without considering read, when you do:

mycmd <<< $myvar

seems to be equivalent to:

printf '%s\n' "$myvar" | mycmd

which is similar to:

echo "$myvar" | mycmd

except that echo interprets some backslash escapes and therefore could mess up your string.

So we see that <<< is a convenient and concise way to pass a variable (or other expansions) to the stdin of a command.

As a concrete example:

myvar="$(printf '01\n23\n45')"
sed 's/./A/' <<< $myvar

or:

sed 's/./A/' <<< $'01\n23\n45'

or:

myvar="$(printf '01\n23\n45')"
printf '%s\n' "$myvar" | sed 's/./A/'

all use sed to replace the first letter of each line with A giving output:

A1
A3
A5