为什么“意外标记附近出现语法错误”?

为什么“意外标记附近出现语法错误”?

我有大约 10k(大约 180x50x2)CSV 文件,我想将它们连接在一起,如下所示,但内部 for 循环由于某些原因而失败syntax error;我看不到其中的错误lastFile

#!/bin/bash
dir='/home/masi/CSV/'
targetDir='/tmp/'
ids=(118 119 120)
channels=(1 2)
for id in ids;

        do
        for channel in channels;

                # example filename P209C1T720-T730.csv
                lastFile="$dir'P'$id'C'$channel'T1790-T1800.csv'"
                # show warning if last file does not exist
                if [[ -f $lastFile ]]; then
                    echo "Last file "$lastFile" is missing" 
                    exit 1
                fi

                filenameTarget="$targetDir'P'$id'C'$channel'.csv'"
                cat $dir'P'$id'C'$channel'T'*'.csv' > $filenameTarget

        done;
done

错误

makeCSV.sh: line 12: syntax error near unexpected token `lastFile="$dir'P'$id'C'$channel'T1790-T1800.csv'"'
makeCSV.sh: line 12: `      lastFile="$dir'P'$id'C'$channel'T1790-T1800.csv'"'

操作系统:Debian 8.5
Linux 内核:4.6 向后移植

答案1

do你的第二个 for 循环中缺少一个:

for id in ids;

        do
        for channel in channels; do # <----- here ----

                # example filename P209C1T720-T730.csv
                lastFile="$dir'P'$id'C'$channel'T1790-T1800.csv'"
                # show warning if last file does not exist
                if [[ -f $lastFile ]]; then
                    echo "Last file "$lastFile" is missing" 
                    exit 1
                fi

                filenameTarget="$targetDir'P'$id'C'$channel'.csv'"
                cat $dir'P'$id'C'$channel'T'*'.csv' > $filenameTarget

        done;
done

根据评论中的讨论,我发现您对循环语法感到困惑for

这是循环的粗略语法for

for name in list; do commands; done

do命令之前始终必须有一个命令,命令之后必须有一个;(或换行符) 。done

这是带有更多换行符的变体:

for name in list
do
    commands
done

答案2

它工作正常:

#!/bin/bash
dir='/home/masi/CSV/'
targetDir='/tmp/'
ids=(118 119 120)
channels=(1 2)
for id in ids ; do

        # Add do after ';'
        for channel in channels ; do

                # example filename P209C1T720-T730.csv
                lastFile="$dir'P'$id'C'$channel'T1790-T1800.csv'"
                # show warning if last file does not exist
                if [[ -f $lastFile ]] ; then
                    echo "Last file "$lastFile" is missing" 
                    exit 1
                fi

                filenameTarget="$targetDir'P'$id'C'$channel'.csv'"
                cat $dir'P'$id'C'$channel'T'*'.csv' > $filenameTarget

        done
done

为了将来使用 bash 调试器:bash -x /路径/到/你的/脚本

相关内容