How to print multiple line string on bash

To display some pre-formatted text onto screen, we need the following 2 capabilities:

Construct Multiple Text

There are 2 ways to construct multiple line strings:

  • String literal

    String Literal
    1
    2
    3
    4
    5
    text = "
    First Line
    Second Line
    Third Line
    "
  • Use cat

    cat
    1
    2
    3
    4
    5
    6
    text = $(cat << EOF
    First Line
    Second Line
    Third Line
    EOF
    )

For some reason, echo command will eat all the line break in the text, so we should use printf instead of echo.
And printf supports back-slash-escape, so we can use \n to print a new-line on screen.

Distribute files to multiple servers via scp

The most common task when operating the servers is to distribute a file to multiple servers.
So I wrote a piece of shell script to solve this problem:

mscp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/bin/bash
echo "mscp <source file> <target dir>"
SourceFile=$1
TargetDir=$2
echo "Copy $SourceFile to $TargetDir as $RemoteUser"
echo "Enter the servers:"
if [-f $SourceFile ]
then
printf "File found, preparing to transfer\n"
while read server
do
scp -p $SourceFile ${server}:$TargetDir
done
else
printf "File \"$SourceFile\"not found\n"
exit 1
fi
exit 0

call the script mscp <source file> <target dir>, then the script will ask you the list of target servers. So you can type them one by one. If the remote user is different than you current user, you can also explicitly identify it by typeing user@server

Beside the previous scenario, there is a more common sceanrio, that you have got a server list stored in afile already. Then instead of type the servers line by line, you can pipe the file content to the script.
e.g:

Read server list from file
1
cat server_list.txt > mscp src_files dest_path