[英]How to tar the n most recent files
I am trying to create a script that foreach directoy in the folder folder, only the n most recent files are to be compressed. 我正在尝试创建一个在文件夹文件夹中预先指定的脚本,仅压缩n个最新文件。
However, I am having trouble with the multiple word files. 但是,我遇到了多个word文件的问题。 I need a way to wrap them in quote marks so the tar command knows wich is each file. 我需要一种方法将它们包装在引号中,以便tar命令知道每个文件。
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
if [ ! -d ~/backup ]; then mkdir ~/backup fi
You can simplify by this : 你可以简化:
[[ ! -d ~/backup ]] && mkdir ~/backup
Now to answer your question : 现在回答你的问题:
$ ls -t|head -10
file with spaces
file
test.txt
test
test.sh
$ lstFiles=""; while read; do lstFiles="$lstFiles \"$REPLY\""; done <<< "$(ls -t|head -10)"
$ echo $lstFiles
"file with spaces" "file" "test.txt" "test" "test.sh"
See how to read a command output or file content with a loop in Bash to read more details. 了解如何使用Bash中的循环读取命令输出或文件内容以阅读更多详细信息。
Several workarounds if you want to stick to one-liners - simplest is probably to use 'tr' and introduce wildcard for spaces: 如果你想坚持使用单行的几种解决方法 - 最简单的可能是使用'tr'并为空格引入通配符:
echo tar zcf ~/backup/"$i".tar.gz "
ls -t | head -10 | tr ' ' '?'"
echo tar zcf ~/backup/"$i".tar.gz "
ls -t | head -10 | tr ' ' '?'"
-rw-rw-r-- 1 dale dale 35 Apr 6 09:11 test 1_dummy.txt
-rw-rw-r-- 1 dale dale 35 Apr 6 09:11 test 2_dummy.txt
-rw-rw-r-- 1 dale dale 35 Apr 6 09:11 test 3_dummy.txt
-rw-rw-r-- 1 dale dale 35 Apr 6 09:11 test 4_dummy.txt
-rw-rw-r-- 1 dale dale 35 Apr 6 09:11 test 5_dummy.txt
-rw-rw-r-- 1 dale dale 35 Apr 6 09:11 test 6_dummy.txt
-rw-rw-r-- 1 dale dale 35 Apr 6 09:11 test 7_dummy.txt
-rw-rw-r-- 1 dale dale 35 Apr 6 09:11 test 8_dummy.txt
-rw-rw-r-- 1 dale dale 35 Apr 6 09:11 test 9_dummy.txt
-rw-rw-r-- 1 dale dale 35 Apr 6 09:11 test 10_dummy.txt
-rw-rw-r-- 1 dale dale 35 Apr 6 09:11 test 11_dummy.txt
$ tar cvf TEST.tar $(ls -t | head -5 | tr ' ' '?')
test 11_dummy.txt
test 10_dummy.txt
test 9_dummy.txt
test 8_dummy.txt
test 7_dummy.txt
Another option might be to redirect to a file and then use '-T': 另一种选择可能是重定向到文件然后使用'-T':
ls -t | head > /tmp/10tarfiles.txt
echo tar zcf ~/backup/"$i".tar.gz -T /tmp/10tarfiles.txt"
rm /tmp/10tarfiles.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.