Complete Communications Engineering

Two ways to do this are using pipes and using here documents.  Pipes on the Linux command line allow the output of one command to be used as input for another.  Output is from standard out, and input is from standard in.  Normally standard out would be directed to the console so it can be read, but a pipe (‘|’ character) will re-direct it as input to the command after the pipe.  The following example demonstrates this:

#!/bin/sh

 

# Define a command that takes input from stdin

decide_what_to_do() {

    read NUMBER

    read WEATHEROK

    case $WEATHEROK in

        [Yy]* ) echo “Let’s invite $NUMBER friends to the beach.”;;

        * ) echo “Let’s stay home and read $NUMBER books.”;;

    esac

}

 

# Run the command with various inputs

printf “5\ny” | decide_what_to_do

printf “2\nn” | decide_what_to_do

 

# Expected output:

# >./decide.sh

# >Let’s invite 5 friends to the beach.

# >Let’s stay home and read 2 books.

This example uses the ‘printf’ command to pipe an answer for multiple prompts into the command.  Each answer is separated by a ‘\n’ character.

When lots of input is required, here documents can be easier to read.  Here documents use a re-direction operator and a delimiter to specify a multi-line command that will be fed into another command.  In this case, the input appears after the command that will use it.  The delimiter appears at the beginning and end of the here document, and it can be anything as long as it doesn’t appear in the contents of the here document.  One practical use for a here document is to feed commands into ‘sftp’ to transfer multiple files at once.  The following example demonstrates this:

#!/bin/sh

 

NAME=bob

COLOR=red

 

# Grab some files using SFTP.  Note that SFTP will still prompt for a

# password, even with the heredoc input.

sftp $NAME@192.168.0.1 << EOF

get /home/$NAME/list.txt

get /home/$NAME/data.dat

get /home/$NAME/schedule.txt

get /home/$NAME/art/$COLOR*.jpg

EOF