2012-11-08 58 views
0

这是我的第一个bash脚本,用于将我的内容同步到服务器。我想通过要同步的文件夹作为参数。但是,它不能按预期工作。如果条件错误,bash脚本

这是我的脚本(保存为sync.sh):

echo "STARTING SYNCING... PLEASE WAIT!" 
var="$1" ; 
echo "parameter given is $var" 

if [ "$var"=="main" ] || [ "$var"=="all" ] ; then 
    echo "*** syncing main ***" ; 
    rsync -Paz /home/chris/project/main/ [email protected]_host:webapps/project/main/ 
fi 

if [ "$var"=="system" ] || [ "$var"=="all" ] ; then 
    echo "*** syncing system ***" ; 
    rsync -Paz /home/chris/project/system/ [email protected]_host:webapps/project/system/ 
fi 

if [ "$var"=="templates" ] || [ "$var"=="all" ] ; then 
    echo "*** syncing templates ***" ; 
    rsync -Paz /home/chris/project/templates/ [email protected]_host:webapps/project/templates/ 
fi 

这我的输出:

[email protected] ~/project/ $ sh ./sync.sh templates 
STARTING SYNCING... PLEASE WAIT! 
parameter given is templates 
*** syncing main *** 
^Z 
[5]+ Stopped     sh ./sync.sh templates 

虽然我给的 “模板” 作为一个参数,它忽略它。为什么?

回答

0

基于下面的意见,这是我的建议修正后的脚本:

#!/bin/bash 
echo "STARTING SYNCING... PLEASE WAIT!" 
var="$1" ; 
echo "parameter given is $var" 

if [ "$var" == "main" -o "$var" == "all" ] ; then 
    echo "*** syncing main ***" ; 
    rsync -Paz /home/chris/project/main/ [email protected]_host:webapps/project/main/ 
fi 

if [ "$var" == "system" -o "$var" == "all" ] ; then 
    echo "*** syncing system ***" ; 
    rsync -Paz /home/chris/project/system/ [email protected]_host:webapps/project/system/ 
fi 

if [ "$var" == "templates" -o "$var" == "all" ] ; then 
    echo "*** syncing templates ***" ; 
    rsync -Paz /home/chris/project/templates/ [email protected]_host:webapps/project/templates/ 
fi 
+0

-1'[“$ var”==“main”|| “$ var”==“all”]'不起作用。 – dogbane

+1

'[“$ var”==“main”|| “$ var”==“all”]'应该改为'[“$ var”==“main”-o“$ var”==“all”]' – anishsane

+1

或者它可以改为使用双括号即'[[“$ var”==“main”|| “$ var”==“all”]]' – dogbane

2

您需要在==运算符两边的空间。将其更改为:

if [ "$var" == "main" ] || [ "$var" == "all" ] ; then 
    echo "*** syncing main ***" ; 
    rsync -Paz /home/chris/project/main/ [email protected]_host:webapps/project/main/ 
fi 
+0

谢谢。我曾经在'=='附近有空格,但是我得到了这个:'开始同步......请等待! 给出的参数是模板 ./sync.sh:5:[:模板:意外运算符 ./sync.sh:5:[:模板:意外运算符 ./sync.sh:10:[:模板:意外运算符 ./sync.sh:10:[:模板:意外运算符 ./sync.sh:15:[:模板:意外运算符 ./sync.sh:15:[:模板:意外运算符 ./sync。 sh:20:[:templates:unexpected operator ./sync.sh:20:[:templates:unexpected operator' – xpanta