linux定时任务执行

#!/bin/bash

# Define the directory where logs are stored
LOG_DIR="/data/scripts"

# Define the maximum file size in bytes (10GB = 10 * 1024 * 1024 * 1024)
MAX_SIZE=$((10*1024*1024*1024))

# Log file for recording execution logs
LOG_FILE="/var/log/cleanup_logs.log"

# Log the current date/time and action
echo "$(date +'%Y-%m-%d %H:%M:%S') - Starting log cleanup" >> "$LOG_FILE"

# Find and delete log files larger than MAX_SIZE bytes recursively
find "$LOG_DIR" -type f -name "*.log" -size +$MAX_SIZEc -print0 | while IFS= read -r -d '' file; do
    echo "$(date +'%Y-%m-%d %H:%M:%S') - Deleting $file" >> "$LOG_FILE"
    rm -f "$file"
done

# Log the completion
echo "$(date +'%Y-%m-%d %H:%M:%S') - Log cleanup completed" >> "$LOG_FILE"

每30分钟执行一次

*/30 * * * * /home/user/scripts/myscript.sh

-bash: ./deploy.sh: /bin/bash^M: bad interpreter: No such file or directory

报错解释:

这个错误表明你尝试执行名为 deploy.sh 的脚本文件时遇到了问题。具体来说,是因为该脚本文件的第一行(shebang行)中的解释器路径 /bin/bash^M 后面跟了一个 ^M,这个字符实际上是Windows风格的行结束符\r\n(即CR+LF),而Unix/Linux系统中只使用LF作为行结束符。因此,shell在尝试执行时找不到 /bin/bash^M 指定的解释器,因为这个路径是无效的。

解决方法:

你需要将脚本中的Windows风格的行结束符\r\n转换为Unix/Linux的行结束符\n。可以使用dos2unix命令或者sed命令来转换文件。

执行以下命令之一:

如果你有 dos2unix 工具安装:

dos2unix deploy.sh

如果你只有 sed 命令:

sed -i 's/\r$//' deploy.sh

转换完成后,你应该能够正常执行脚本:

./deploy.sh