3

In Linux Shell script, I am trying to trace each command status (either Success or Failure) in a log file.

Below is my code snippet to log the entries in a log file.

scp $user@$host:$from $to 2>error.txt

command_run_status=$?

if [[ $command_run_status == 0 ]]; then log_message="secure copy on ("${host}") with ("${user}") is successful"; else log_message="error copying files "`cat error.txt`; fi

./logging.sh "$CURRENT_PID" "$log_message" "D"

Log file is created with an entry as below:

DEBUG 2019-06-21 10:05:35,347 BST [pid1234] [autouser]: error copying files usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file] [-l limit] [-o ssh_option] [-P port] [-S program] [[user@]host1:]file1 [...] [[user@]host2:]file2

However, I am expecting the log entry as below - error.txt file content with new line character.

DEBUG 2019-06-21 10:05:35,347 BST [pid1234] [autouser]: error copying files

usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]

           [-l limit] [-o ssh_option] [-P port] [-S program]

           [[user@]host1:]file1 [...] [[user@]host2:]file2

Content of error.txt is as below:

usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]

           [-l limit] [-o ssh_option] [-P port] [-S program]

           [[user@]host1:]file1 [...] [[user@]host2:]file2

Can someone comment on the cause of displaying multi-line file content are displaying in a single line in the log file?

What changes are required on the command to print the error file content (with newline character) in the log file?

PraveenKS
  • 1,145
  • 3
  • 13
  • 28

1 Answers1

2
`cat error.txt`

Bash performs the expansion by executing command in a subshell environment and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting.

To prevent word splitting, include the command substitution in double quotes.

echo $(printf 'a\nb\nc')

prints

a b c

while

echo "$(printf 'a\nb\nc')"

prints

a
b
c

(Prefer $(command) to old style `command`).

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243