bash脚本如果条件错误

时间:2012-11-08 08:38:13

标签: 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/ user@remote_host:webapps/project/main/ 
fi

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

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

这是我的输出:

chris@mint-desktop ~/project/ $ sh ./sync.sh templates
STARTING SYNCING... PLEASE WAIT!
parameter given is templates
*** syncing  main ***
^Z
[5]+  Stopped                 sh ./sync.sh templates

虽然我将“模板”作为参数,但它忽略了它。为什么呢?

2 个答案:

答案 0 :(得分:2)

==运算符两侧需要一个空格。将其更改为:

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

答案 1 :(得分: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/ user@remote_host:webapps/project/main/ 
fi

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

if [ "$var" == "templates" -o "$var" == "all" ] ; then
    echo "*** syncing  templates ***" ;
    rsync -Paz /home/chris/project/templates/ user@remote_host:webapps/project/templates/ 
fi