linux - cat 单行显示多行文件内容

标签 linux bash concatenation logfile

在 Linux Shell 脚本中,我试图在日志文件中跟踪每个命令状态(成功或失败)。

下面是我的代码片段,用于将条目记录在日志文件中。

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"

创建的日志文件包含如下条目:

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

但是,我希望日志条目如下 - 带有换行符的 error.txt 文件内容。

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

error.txt内容如下:

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

有人可以评论显示多行文件内容在日志文件中显示在单行中的原因吗?

在日志文件中打印错误文件内容(带换行符)的命令需要做哪些改动?

最佳答案

`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.

为防止单词拆分,请将命令替换包含在双引号中。

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

打印

a b c

同时

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

打印

a
b
c

(首选 $(command) 而不是旧式的 `command`)。

关于linux - cat 单行显示多行文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56700703/

相关文章:

ffmpeg 视频连接 - 音频/视频轨道同步

java - 使用 select 和 Concat 的 JPA JPQL 请求

linux - grep 第 n 行 linux 的一部分

c++ - 使用 C++ 在 Linux 上锁定/防止编辑源文件

bash - 从文件中提取单词

c - 与指针的动态连接

linux - Xdotool 在 Raspberry Pi 上失败

linux - 当没有人等待条件时 pthread_cond_broadcast 的性能

bash - 在 bash 中连接字符串会覆盖它们

python-3.x - 为什么在 Python 中读取文件时会出现撇号 ("' ") turn into ▒' s?