Friday, April 19, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  6] [ 0]  / answers: 1 / hits: 2317  / 2 Years ago, wed, april 6, 2022, 10:55:42

I am trying to create a script that foreach directoy in the folder folder, only the n most recent files are to be compressed.



However, I am having trouble with the multiple word files. I need a way to wrap them in quote marks so the tar command knows wich is each file.



Here is my script so far:



#!/bin/bash

if [ ! -d ~/backup ]; then
mkdir ~/backup
fi

cd ~/folder
for i in *; do
if [ -d "$i" ]; then
original=`pwd`
cd $i
echo tar zcf ~/backup/"$i".tar.gz "`ls -t | head -10`"
cd $original
fi
done
echo "Backup copied in $HOME/backup/"
exit 0

More From » bash

 Answers
1

xargs to the rescue! One way is to use xargs to create argument list but put each file inside of quotes:



echo `ls -t1 | head -10 | xargs -I'{}' echo "{}"`


Other option it to use xargs to directly call tar in append mode (-r) and then compressing it at the end (you cannot create compressed archives in append mode):



ls -t | head -10 | xargs -I'{}' tar -rvf ~/backup/"$i".tar '{}'
gzip ~/backup/"$i".tar


The advantage of the 2nd approach is that you can change 10 to any other, even very high number and it will still work without getting too long argument list.


[#26175] Friday, April 8, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brailloni

Total Points: 122
Total Questions: 108
Total Answers: 108

Location: North Korea
Member since Tue, Apr 4, 2023
1 Year ago
brailloni questions
Tue, Jun 21, 22, 21:51, 2 Years ago
Thu, Jul 29, 21, 05:25, 3 Years ago
Sat, Apr 2, 22, 17:32, 2 Years ago
Mon, Oct 31, 22, 21:39, 1 Year ago
;