2012-11-08 83 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