Linux

只需將 zip 文件移動到單獨的目錄並解壓縮它們

  • June 2, 2020

我有一個目錄**/home/ubuntu/uploads**。我需要檢查它是否包含任何 zip 文件。如果它包含,那麼我需要根據日期將最舊的修改文件移動到另一個名為**/home/ubuntu/temp的目錄。然後我需要將我們在 /home/ubuntu/temp中獲得的 zip 文件解壓縮 到一個名為/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 文件名。

如果有人可以提出更好和改進的版本,請

這有效..謝謝大家!

#!/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

引用自:https://unix.stackexchange.com/questions/589653