Shell脚本中的布尔表达式

时间:2008-09-07 20:51:35

标签: bash shell expression

将以下内容作为布尔表达式的“正确”方法是什么?

for i in `ls $1/resources`; do
    if [ $i != "database.db" ]
    then
        if [ $i != "tiles" ]
        then
            if [ $i != "map.pdf" ]
            then
                if [ $i != "map.png" ]
                then
                    svn export -q $1/resources/$i ../MyProject/Resources/$i
...

5 个答案:

答案 0 :(得分:11)

其他解决方案有几个常见错误: http://www.pixelbeat.org/programming/shell_script_mistakes.html

  1. for i in $(ls ...)多余/有问题 只需:for i in $1/resources*; do ...

  2. [ $i != file1 -a $1 != file2 ]这实际上有两个问题。

    一个。 $i未引用,因此带空格的名称将导致问题

    -a如果stat文件没有短路({I}知道以上不是stat文件),效率很低。

  3. 所以请尝试:

    for i in $1/resources/*; do
        if [ "$i" != "database.db" ] &&
           [ "$i" != "tiles" ] &&
           [ "$i" != "map.pdf" ] &&
           [ "$i" != "map.png" ]; then
            svn export -q "$i" "../MyProject/Resources/$(basename $i)"
        fi
    done
    

答案 1 :(得分:7)

更短:

for i in `ls $1/resources`; do
  if [ $i != databse.db -a $i != titles -a $i != map.pdf ]; then
    svn export -q $1/resources/$i ../MyProject/Resources/$i
  fi
done;

if表达式中的-a等效于shell-tests中的布尔值。有关详情,请参阅man test

答案 2 :(得分:3)

考虑使用案例声明:

for i in $(ls $1/resources); do
    case $i in
        database.db|tiles|map.pdf|map.png)
           ;;
        *)
           svn export -q $1/resources/$i ../MyProject/Resources/$i;;
    esac
done

答案 3 :(得分:1)

for i in `ls $1/resources`; do
    if [ $i != "database.db" ] && [ $i != "tiles" ] && [ $i != "map.pdf" ] && [ $i != "map.png" ]; then
        svn export -q $1/resources/$i ../MyProject/Resources/$i

答案 4 :(得分:0)

为了将来参考,新[[测试运算符是首选。接受的答案很接近,所提到的一切都适用,但答案需要大量的引用和多次测试的调用。

首选方法如下:

for i in $1/resources/*; do
    if [[ $i != "database.db" && $i != "tiles" &&
                $i != "map.pdf" && $i != "map.png" ]]; then
        svn export -q "$i" "../MyProject/Resources/$(basename $i)"
    fi
done