只需将 zip 文件移动到单独的目录并解压缩

只需将 zip 文件移动到单独的目录并解压缩

我有一个目录/home/ubuntu/上传。我需要检查它是否包含任何 zip 文件。如果它包含,那么我需要根据日期将最旧的修改文件移动到另一个名为/home/ubuntu/temp。然后我需要解压我们得到的zip文件 /home/ubuntu/temp 到一个名为/home/ubuntu/s3。最后我需要将文件标记为已成功移动。

这是我在 bash 脚本中所做的 ->

#!/bin/bash

if [[ -z  `ls -t /home/ubuntu/uploads/*.zip | tail -1` ]] ; then
    echo 'No new zip file to move !'
    exit
fi

TIME=`date +%Y-%m-%d_%H-%M-%S`
UPLOADS='/home/ubuntu/uploads'
TEMP='/home/ubuntu/temp'
BUCKET='/home/ubuntu/s3'

FILENAME=`ls -t /home/ubuntu/uploads/*.zip | tail -1 | xargs -n 1 basename `
FILEPATH=`ls -t /home/ubuntu/uploads/*.zip | tail -1`

cp $FILEPATH $TEMP
unzip -u $TEMP/"$FILENAME" -d $BUCKET
rm -rf  $TEMP/*
mv /home/ubuntu/uploads/"$FILENAME"  /home/ubuntu/uploads/"$FILENAME".success.$TIME

它可以工作,但无法处理包含空格的 zip 文件名。

如果有人可以建议一个更好的和改进的版本,请

答案1

这有效..谢谢大家!

#!/bin/bash

# logs last error
#exec 3>&1 4>&2
#trap 'exec 2>&4 1>&3' 0 1 2 3
#exec 1>log.out 2>&1

# check for file names with space and rename
for file in /home/ubuntu/uploads/*' '*
do
  if [ -e "${file// /_}" ]
  then
    printf >&2 '%s\n' "Warning, skipping $file as the renamed version already exists"
    continue
  fi

  mv -- "$file" "${file// /_}"
done

# check for zip files
if [[ -z  `ls -t /home/ubuntu/uploads/*.zip | tail -1` ]] ; then
    echo 'No new zip file to move !'
    exit
fi

# check for bad zip file and remove
shopt -s dotglob nullglob globstar
for file in /home/ubuntu/uploads/*.zip; do
    [[ -r $file ]] || continue
    unzip -t "$file" >/dev/null 2>&1 ||  rm -f "$file"
done


TIME=`date +%Y-%m-%d_%H-%M-%S`
UPLOADS='/home/ubuntu/uploads'
TEMP='/home/ubuntu/temp'
BUCKET='/home/ubuntu/s3'

FILENAME=`ls -t /home/ubuntu/uploads/*.zip | tail -1 | xargs -n 1 basename `
FILEPATH=`ls -t /home/ubuntu/uploads/*.zip | tail -1`

cp $FILEPATH $TEMP

unzip -u $TEMP/$FILENAME -d $BUCKET

rm -rf  $TEMP/*

mv /home/ubuntu/uploads/"$FILENAME"  /home/ubuntu/uploads/"$FILENAME".success.$TIME

相关内容