我的备份脚本有点问题。它使用for
循环使用tar
归档给定目录中的任何内容。它完美地列出了目录,并为每个目录创建了我想要的单独存档,但变量没有列出要备份的目录的路径。谁能让我知道如何确保变量填充正确的信息?
这是脚本:
#!/bin/bash
set -xv
dirs=$(ls /home/phoenix/testarchive)
dest="/home/phoenix/backup/"
archive=".tar.bz2"
clear
echo "Archiving data..."
for dirs in $dirs
do
echo "Archiving $dirs..."
tar cjf "${dest}${dirs}_$(date +%F)${archive}" $dirs
echo "Archive complete!!"
done
echo "All archives created!!"
echo "Test created archive to ensure validity."
ls -lh $dest
这是我的错误输出:
echo "Archiving data..."
+ echo 'Archiving data...'
Archiving data...
for dirs in $dirs
do
echo "Archiving $dirs..."
tar cjf "${dest}${dirs}_$(date +%F)${archive}" $dirs
echo "Archive complete!!"
done
+ for dirs in $dirs
+ echo 'Archiving folder1...'
Archiving folder1...
++ date +%F
+ tar cjf /home/phoenix/backup/folder1_2017-07-18.tar.bz2 folder1
tar: folder1: Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors
+ echo 'Archive complete!!'
Archive complete!!
+ for dirs in $dirs
+ echo 'Archiving folder2...'
Archiving folder2...
++ date +%F
+ tar cjf /home/phoenix/backup/folder2_2017-07-18.tar.bz2 folder2
tar: folder2: Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors
+ echo 'Archive complete!!'
Archive complete!!
echo "All archives created!!"
+ echo 'All archives created!!'
All archives created!!
echo "Test created archive to ensure validity."
+ echo 'Test created archive to ensure validity.'
Test created archive to ensure validity.
ls -lh $dest
+ ls -lh /home/phoenix/backup/
total 8.0K
-rw-r--r-- 1 phoenix phoenix 46 Jul 18 13:48 folder1_2017-07-18.tar.bz2
-rw-r--r-- 1 phoenix phoenix 46 Jul 18 13:48 folder2_2017-07-18.tar.bz2
像我提到的那样,脚本正在命名我想要的方式,但实际的数据存档并没有被创建。我确信ls
是问题,但我不知道有任何其他方法可以得到理想的结果......
答案 0 :(得分:1)
仔细阅读错误消息并理解它们总是好的:
+ tar cjf /home/phoenix/backup/folder1_2017-07-18.tar.bz2 folder1 tar: folder1: Cannot stat: No such file or directory tar: Exiting with failure status due to previous errors
这意味着无法找到folder1
。
为什么?
folder1
在哪里?
它位于/home/phoenix/testarchive
目录中。
执行脚本时
是/home/phoenix/testarchive
中的当前工作目录?
可能不是。
我建议写这样的脚本:
#!/bin/bash
set -xv
dirs_basedir=/home/phoenix/testarchive
dest="/home/phoenix/backup"
archive=".tar.bz2"
clear
echo "Archiving data..."
for path in "$dirs_basedir"/*
do
basedir=${path%/*}
dir=${path##*/}
echo "Archiving $dir in $basedir..."
tar cjf "${dest}/${dirs}_$(date +%F)${archive}" -C "$basedir" "$dir"
echo "Archive complete!!"
done
echo "All archives created!!"
echo "Test created archive to ensure validity."
ls -lh $dest
虽然这可能看起来比原来稍微复杂一点, 它更安全。
答案 1 :(得分:0)
简短的回答是tar使用相对路径。我从这个错误信息中得出了这个结论:
tar: folder1: Cannot stat: No such file or directory
无论如何,我建议你cd到父目录。 你可以在运行脚本之前通过cd'ing测试我的理论。
cd /home/phoenix/testarchive
您必须小心备份文件的位置,因为它们也将放在当前目录中,除非您在tar语句中放置路径。