我有以下脚本:
/usr/bin/daily-execution
#!/bin/bash
log_folder=/var/log/hans-keeper
now=$(date +"%Y-%m-%d-%H:%M:%S")
if [ ! -d "/var/log/hans-keeper" ]
then
mkdir /var/log/hans-keeper
fi
target_file="$log_folder/$now"
exec_log(){
echo "executing $1 and log into: $target_file"
result=$(sudo $1)
echo "$1" >> $target_file
echo "-------------------------------------------------" >> $target_file
printf "%s\n" $result >> $target_file
echo "-------------------------------------------------" >> $target_file
echo "" >> $target_file
}
exec_log /usr/bin/hans-keeper
exec_log /usr/bin/move-sync-staging
有/usr/bin/hans-keeper
一个多线回显,如下所示:
echo "line 1"
echo "line 2"
echo "line 3"
以及move-sync-staging
.
我看到/usr/bin/hans-keeper
直接在shell中执行会打印:
line 1
line 2
line 3
但是当我从结果打开日志文件时/usr/bin/daily-execution
,它只是打印:
line 1line 2line 3
看起来,当/usr/bin/hans-keeper
直接在 shell 中执行脚本时,输出不包含任何换行符。
我非常感谢您帮助解决此问题并改进我的脚本。
答案1
echo "executing $1 and log into: $target_file" result=$(sudo $1) echo "$1" >> $target_file echo "-------------------------------------------------" >> $target_file printf "%s\n" $result >> $target_file echo "-------------------------------------------------" >> $target_file echo "" >> $target_file
未加引号的扩展$result
是原因。使用{ cmd1; cmd2 } >> file
而不是单独的重定向。
exec_log() {
echo "executing $1 and log into: $target_file"
{
echo "$1"
echo "-------------------------------------------------"
sudo "$1"
echo "-------------------------------------------------"
echo ""
}>> "$target_file"
}