tee -a:没有这样的文件或目录

问题描述 投票:0回答:3

请看下面的代码。

#!/bin/sh
LOG_FILE=/home/admin/scriptLogs.log
rm -f ${LOG_FILE}
echo "`date`:: Script Execution Started" | tee -a ${LOG_FILE}
DATABASE ACCESS CODE 2>&1
echo "`date`:: Script Execution Successful " | tee -a {$LOG_FILE}
exit 0

它产生以下输出:

> Tue Feb  7 12:14:49 IST 2017:: Script Execution Started 
> tee:{/home/admin/scriptLogs.log}: No such file or directory 
> Tue Feb  7 12:14:49 IST 2017:: Script Execution Successfull

但是,该文件存在于指定位置。除了最后一个 echo 语句之外,它还会附加数据。为什么会有这样的行为?

bash tee
3个回答
2
投票

确保在扩展变量之前始终引用变量以避免重新解释(请在此处阅读:http://www.tldp.org/LDP/abs/html/quotingvar.html) 另外,您应该将 LOG_FILE 定义为字符串(请注意下面的引号):

LOG_FILE="/home/admin/scriptLogs.log"

话虽如此,正如 @codeforester 提到的,你的脚本中有一个拼写错误

此外,您打印执行成功,但没有检查它是否确实成功。

所以你的代码应该如下所示:

    #!/bin/sh
    LOG_FILE="/home/admin/scriptLogs.log"
    rm -f "$LOG_FILE"
    echo "`date`:: Script Execution Started" | tee -a "$LOG_FILE"
    DATABASE ACCESS CODE 2>&1
    if [ $? -eq 0 ]; then
      echo "`date`:: Script Execution Successful " | tee -a "$LOG_FILE"
    else
      ...
    exit 0

注意:我已经删除了大括号,因为这里不需要它们(尽管这样做不是一个错误)


0
投票

正如@codeforester指出的,使用:

#!/bin/sh
LOG_FILE=/home/admin/scriptLogs.log
rm -f ${LOG_FILE}
echo "`date`:: Script Execution Started" | tee -a ${LOG_FILE}
DATABASE ACCESS CODE 2>&1
echo "`date`:: Script Execution Successful " | tee -a ${LOG_FILE}
exit 0

0
投票

就我而言, 我定义了一个像

这样的变量
LOG_FILE="~/test.log"
some_command | tee -a $LOG_FILE

我了解到“~”不会在双引号中扩展。 在这种情况下正确的方法是

# Use absolute path
LOG_FILE="/path/to/home/test.log"

# OR

# Use $HOME environment variable
LOG_FILE="$HOME/test.log"
© www.soinside.com 2019 - 2024. All rights reserved.