2013-05-20 48 views
1

我正在尝试创建一个BASH脚本来备份到外部驱动器。我会运行这个脚本来检查连接哪个驱动器,然后运行rsync。我是BASH的新手,并不能完全弄清楚它是否是其他人。谁能帮忙?我在想的是。bash if then else if back up to two drives

If [ /Volumes/Drive_1] 
then 
    sudo rsync -avx /Volumes/1/2\ __3__/ /Volumes/Drive_1 
else 
    If [ /Volumes/Drive_2] 
then 
    sudo rsync -avx /Volumes/1/2\ __3__/ /Volumes/Drive_2 
fi 
+1

为什么另起炉灶呢?有很多很棒的备份工具/脚本,如果需要的话,其中许多可以使用'rsync'作为后端。 –

回答

2

做多路径完全相同的东西往往是最简单的使用变量和

# Stores all Paths to BackupPaths 
BackupPaths=("/Path/to/First" "/Path/to/second" ....) 

# Iterates for each Path and stores current in volume 
# $volume allows for accessing the content of the variable 
for volume in "${BackupPaths[@]}"; do 
    if [ -d "$volume" ] 
    then 
     sudo rsync -avx /Volumes/1/2\ __3__/ "$volume" 
    fi 
done 
+3

使用字符串代替数组是邪恶的。你想备份“/ Users /名字姓氏/备份我的内容”的内容?使用正确的数组:“BackupPaths =(”/ Path/to/First“”/ Path/to/second“”/ Path/containing whitespace“)',然后:'用于$ {BackupPaths [@]}中的卷” ;做rsync ...“$ volume”; (注意扩展周围的引号;它们是强制性的以避免错误)。 –

+0

@Charles Duffy:谢谢,你当然是对的,忘了关于空白处理......给你的提示添加了答案 – Legionair

+2

我做了一些进一步的调整 - 仍然引用了bug。 –

3

首先,它if,不If(情况等事项)。要检查驱动器是否存在,您需要查看给定的字符串是否指定目录,因此您需要使用-d主驱动器。

if [ -d /Volumes/Drive_1 ] 
then 
    sudo rsync -avx /Volumes/1/2\ __3__/ /Volumes/Drive_1 
elif [ -d /Volumes/Drive_2 ] 
then 
    sudo rsync -avx /Volumes/1/2\ __3__/ /Volumes/Drive_2 
fi 

从它们之间的代码分离[]的空间是必要的。

+0

谢谢。我想我很想发帖子。 – abchase

+0

尽管这确实回答了我的问题,但我认为Legionair的帖子更多是我打算使用的。 – abchase