我正在从 server1 运行一个脚本,该脚本有责任使用 scp 命令根据特定参数将文件从 server2 (这将是参数 ${Server})复制到 server3:
scp -p -qo StrictHostKeyChecking=no user@${Server}:/path/to/source/files/*${EAPdate}* user@hostname3:/path/to/destination/files/
脚本本身应该在运行时创建一个日志。如果一切都按预期工作,并且 EAPdate 参数按应有的方式键入 (YYYYMMDD),则复制命令将按预期工作。
但如果参数键入为 (DDMMYYYY),则复制命令将失败,并出现“无此类文件或目录”错误。
脚本如下:
#!/bin/bash
configuration_file=copy_EAP_files.ini
hostname=$(hostname)
script=$(basename "$0")
start_time=$(date)
start_seconds=${SECONDS}
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
LOGFILE="$(basename $0)_$(date +%Y.%m.%d_%H.%M.%S.log)"
LOGPATH=${DIR}"/logs"
mkdir -p ${LOGPATH}
echo_with_timestamp_and_log() {
message=$1
echo "$(date +"%Y.%m.%d %H:%M:%S") ${message}" | tee -a ${LOGPATH}/${LOGFILE}
}
log_time () {
echo -n "$(date +"%Y.%m.%d %H:%M:%S") "
}
read_parameter() {
variableToRead=$1
errorCodeToThow=$2
# read only lines begining with parameter name
result="$(grep "^$variableToRead" ./${configuration_file} | cut -d' ' -f2)"
if [ "${result}" == "" ]; then
echo_with_timestamp_and_log "ERROR ${2}: $1 variable not found in *.ini file"
exit $2
else
echo "${result}"
fi
}
echo_with_timestamp_and_log "Host: ${hostname}"
echo_with_timestamp_and_log "Script: ${script}"
echo_with_timestamp_and_log "Start time: ${start_time}"
echo_with_timestamp_and_log "______________ Script start _______________"
if [ "$#" -eq 0 ]; then
Server=$(read_parameter Server 101)
EAPdate=$(read_parameter EAPdate 102)
elif [ "$#" -eq 2 ]; then
Server=$1
EAPdate=$2
else
echo_with_timestamp_and_log "Illegal number of parameters"
exit 107
fi
echo_with_timestamp_and_log "server = ${Server}"
echo_with_timestamp_and_log "date = ${EAPdate}"
echo_with_timestamp_and_log "Connecting to AIS server ${Server}"
ssh -T $Server <<EOF | tee -a ${LOGPATH}/${LOGFILE}
$(typeset -f log_time)
log_time
echo "${Server}: Copying the EAP files to designated FTP path"
echo ""
echo "${Server}: Copying the files..."
scp -p -qo StrictHostKeyChecking=no user@${Server}:/path/to/source/files/*${EAPdate}* user@hostname3:/path/to/destination/files/
EOF
echo_with_timestamp_and_log "______________ Script end _________________"
elapsed_time=$((${SECONDS} - ${start_seconds}))
readable_time="$((${elapsed_time}/3600)) h $((${elapsed_time}%3600/60)) min"
echo_with_timestamp_and_log "Host: ${hostname}"
echo_with_timestamp_and_log "Script: ${script}"
echo_with_timestamp_and_log "End time: $(date)"
echo_with_timestamp_and_log "Duration: ${readable_time}"
现在,如果 scp 脚本会出现错误“没有这样的文件或目录”${EAP日期}参数,日志不会捕获此消息。我不明白为什么 - 结果日志没有捕获脚本运行时屏幕上看到的所有消息。
我缺少什么?我应该如何创建 scp 命令以根据运行在日志中传递以下输出:
- success: echo "文件复制成功!"
- 由于“没有这样的文件或目录”错误而失败:echo“文件没有成功复制!源路径中没有这样的文件或目录!”
答案1
根据man bash
,§管道
如果使用 |&,命令的标准错误除了其标准输出之外,还连接到...
你需要更换
ssh -T $Server <<EOF | tee -a ${LOGPATH}/${LOGFILE}
经过
ssh -T $Server <<EOF |& tee -a ${LOGPATH}/${LOGFILE}