11

作为布尔表达式执行以下操作的“正确”方法是什么?

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
...
4

5 回答 5

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没有引用,因此带有空格的名称会导致问题

    湾。-aif ing 文件效率低,stat因为它不会短路(我知道上面不是stating 文件)。

所以改为尝试:

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
于 2008-09-15T15:47:04.653 回答
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 测试中的布尔 AND。更多见man test

于 2008-09-07T21:15:38.563 回答
3

考虑使用case语句:

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
于 2008-09-15T16:04:35.763 回答
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
于 2008-09-07T21:04:57.997 回答
1

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

首选方法类似于:

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
于 2015-07-25T19:10:08.633 回答