bash脚本中的if语句问题

时间:2013-11-07 19:01:57

标签: bash if-statement

我正在尝试为目录中的所有文本文件生成LOAD DATA IN语句到一个输出文件。文件由|分隔或者一个TAB,所以我决定用head -1 $ file命令测试每个文件,看它是否包含一个|并输出正确的负载,但它没有运行。 case语句在没有if语句的情况下运行正常,所以我把它缩小到if语句。这是嵌套if语句的正确语法吗?

 #!/bin/bash


    for file in *.txt

    do

    case $file in

    *_TEST1_*)

    firstLine=`head -1 $file`;

    if [[ $firstLine =~ "|" ]]
    then
    echo "LOAD DATA INFILE '/Data/"$file"' INTO TABLE testtable FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '' LINES TERMINATED BY '\n' ignore 1 lines;" >> output.txt;;
    else
    echo "LOAD DATA INFILE '/Data/"$file"' INTO TABLE testtable FIELDS TERMINATED BY '  ' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '' LINES TERMINATED BY '\n' ignore 1 lines;" >> output.txt;;
    fi

    *_TEST2_*)
    echo "LOAD DATA INFILE '/Data/ "$file"' INTO TABLE testtable2 FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '' LINES TERMINATED BY '\n' ignore 1 lines;" >> output.txt;;

    esac
    done

更新

现在就开始工作,如果遇到同样的问题,请参阅下面的答案。

1 个答案:

答案 0 :(得分:1)

问题是双半冒号的放置,因为双半冒号用于指定case语句的结尾,case语句在if语句之前被关闭。我把它改成了这个,现在它起作用了:

#!/bin/bash


    for file in *.txt

    do

    case $file in

    *_TEST1_*)

    firstLine=`head -1 $file`;

    if [[ $firstLine =~ \| ]]
    then
    echo "LOAD DATA INFILE '/Data/"$file"' INTO TABLE testtable FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '' LINES TERMINATED BY '\n' ignore 1 lines;" >> output.txt;
    else
    echo "LOAD DATA INFILE '/Data/"$file"' INTO TABLE testtable FIELDS TERMINATED BY '  ' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '' LINES TERMINATED BY '\n' ignore 1 lines;" >> output.txt;
    fi

;;

    *_TEST2_*)
    echo "LOAD DATA INFILE '/Data/ "$file"' INTO TABLE testtable2 FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '' LINES TERMINATED BY '\n' ignore 1 lines;" >> output.txt

;;

    esac
    done