How-to: Here Strings

A here string can be considered as a stripped-down form of a here document.
It consists of nothing more than COMMAND <<<$WORD, where $WORD is expanded and fed to the stdin of COMMAND.

As a simple example, consider this alternative to the echo-grep construction.

# Instead of: 
if echo "$VAR" | grep -q txt   
# if [[ $VAR = *txt* ]] 
# etc.

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

Or, in combination with read:

String="This is a string of words."

   read -r -a Words <<< "$String" 
#  The -a option to "read" 
#+ assigns the resulting values to successive members of an array.

echo "First word in String is:    ${Words[0]}"   # This 
echo "Second word in String is:   ${Words[1]}"   # is 
echo "Third word in String is:    ${Words[2]}"   # a 
echo "Fourth word in String is:   ${Words[3]}"   # string 
echo "Fifth word in String is:    ${Words[4]}"   # of 
echo "Sixth word in String is:    ${Words[5]}"   # words. 
echo "Seventh word in String is:  ${Words[6]}"   # (null)
                                                 # Past end of $String.

Related macOS commands

How-to: Here Documents
Here Strings - Advanced Bash-Scripting Guide.
macOS How To


 
Copyright © 1999-2024 SS64.com
Some rights reserved