1

I want to assign the following multiple line string value to a variable in a shell script with the the exact indentations and lines.

Usage: ServiceAccountName LogFile
Where:
      ServiceAccountName - credentials being requested.
      LogFile            - Name of the log file

I have been trying to do this following all the suggestions in: How to assign a string value to a variable over multiple lines while indented? But with no result. Please suggest.

REASON="$(cat <<-EOF
    Usage: ServiceAccountName LogFile
    Where:
      ServiceAccountName - credentials being requested.
      LogFile            - Name of the log file
EOF
)"
echo "$REASON"

Here is my script:

GetBatchCredentials.sh

if [ $# -ne 2 ]
then
   # RETURN INVALID USAGE
   GetBatchCredentials_Result="Error"
   GetBatchCredentials_Reason="$(cat <<-EOF
        Usage: ServiceAccountName LogFile
        Where:
          ServiceAccountName - credentials being requested.
          LogFile            - Name of the log file
    EOF
    )"
else
   //coding...
fi

This scripts is called from the following script:

. /www/..../scripts/GetBatchCredentials.sh arg1 arg2
if [ "$GetBatchCredentials_Result" != "Success" ]
then
   echo "Error obtaining FTP Credentials"
   echo "$GetBatchCredentials_Reason"
   ret=1
else
   echo "Obtained Credentials"
fi

2 Answers2

2

Instead of a here-document with a useless cat, what about either

REASON="\
Usage: ServiceAccountName LogFile
Where:
      ServiceAccountName - credentials being requested.
      LogFile            - Name of the log file"

or

REASON="$(printf '%s\n' \
    "Usage: ServiceAccountName LogFile" \
    "Where:" \
    "      ServiceAccountName - credentials being requested." \
    "      LogFile            - Name of the log file")"
Jens
  • 1,752
  • 4
  • 18
  • 36
0

Your script works for me. All I did differently is add #!/bin/sh at top. Then made it executable and ran it. You could also use sh and the name of your original script.

#!/bin/sh
REASON="$(cat <<-EOF
Usage: ServiceAccountName LogFile
Where:
      ServiceAccountName - credentials being requested.
      LogFile            - Name of the log file
EOF
)"
echo "$REASON"
Jens
  • 1,752
  • 4
  • 18
  • 36
Will M
  • 14
  • I copy pasted the above code from your post to my shell script and it started working. Not sure what made it working though. Thank you. – devlperMoose Jan 21 '16 at 20:52
  • 3
    @pavanbairu The reason is that the EOF end-marker is now not indented and is found. In your original, it is indented and not parsed as the end-marker. – Jens Jan 21 '16 at 20:55