Sunday, May 21, 2017

Shell Scripting: <, << and <<<

This post shows the difference between the three standard input redirection operators: <, << and <<<.

1. <

< allows you to pass data contained in a file to the standard input of a command. The format is:

command < file

Examples:

# replace comma with new-lines:
tr ',' '\n' < file

# read a file line-by-line and do something with each line:
while IFS= read -r line; do
  # do something with each line
  ssh "$line" who -b
done < hosts.txt

2. <<

<< allows you to pass multi-line text (called a here-document) to a command until a specific "token" word is reached. The format is:

command << TOKEN
line 1
line 2
TOKEN

For example:

# query a database
sqsh -S server -D db << END
select * from table
where foo='bar'
go
END

3. <<<

<<< allows you to pass a string of text (called a here-string) to a command. If you find yourself echo-ing text and piping it to a command, you should use a here-string instead. (See my previous post on Useless Use of Echo.) The format is:

command <<< text

Examples:

tr ',' '\n' <<< "foo,bar,baz"

grep "foo" <<< "foo,bar,baz"

mailx -s subject $USER <<< "email body"

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.