为什么这个表达式在 Bash for-for 结构中不展开?

为什么这个表达式在 Bash for-for 结构中不展开?

这有效

#!/bin/bash
dir="/home/masi/Documents/CSV/Case/"
targetDir="/tmp/"
id=118
channel=1
filenameTarget=$targetDir"P"$id"C"$channel".csv"
cat $dir"P"$id"C"$channel"T"*".csv" > $filenameTarget

调试时成功输出bash -x ...

+ dir=/home/masi/Documents/CSV/Case/
+ targetDir=/tmp/
+ id=118
+ channel=1
+ filenameTarget=/tmp/P118C1.csv
+ cat /home/masi/Documents/CSV/Case/P118C1T1000-1010.csv /home/masi/Documents/CSV/Case/P118C1T1010-1020.csv 

for-for 循环中的相同表达式不起作用

#!/bin/bash
dir="/home/masi/Documents/CSV/Case/"
targetDir="/tmp/"
ids=(118 119)
channels=(1 2)
# http://unix.stackexchange.com/a/319682/16920
for id in ids;
        do
        for channel in channels;
                do
                # example filename P209C1T720-T730.csv
                lastFile=$dir'P'$id'C'$channel'T1790-T1800.csv'
                # show error if no last file exists
                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 -x ...

+ dir=/home/masi/Documents/CSV/Case/
+ targetDir=/tmp/
+ ids=(118 119)
+ channels=(1 2)
+ for id in ids
+ for channel in channels
+ lastFile=/home/masi/Documents/CSV/Case/PidsCchannelsT1790-T1800.csv
+ [[ -f /home/masi/Documents/CSV/Case/PidsCchannelsT1790-T1800.csv ]]
+ filenameTarget=/tmp/PidsCchannels.csv
+ cat '/home/masi/Documents/CSV/Case/PidsCchannelsT*.csv'
cat: /home/masi/Documents/CSV/Case/PidsCchannelsT*.csv: No such file or directory

代码2

对于不存在的文件,if 子句也始终为正,这是错误的

#!/bin/bash

dir="/home/masi/Documents/CSV/Case/"
startTimes=( $(seq 300 10 1800) )

id=119
channel=1
# example filename P209C1T720-730.csv
firstFile="${dir}P${id}C${channel}T300-T310.csv"
# show error if no first file exists
if [[ ! -f "${firstFile}" ]]; then
    echo "First file "${firstFile}" is missing" 
    exit 1
fi

cat ${firstFile}

输出

cat: /home/masi/Documents/CSV/Case/P119C1T300-310.csv: No such file or directory
+ for channel in '"${channels[@]}"'
+ for startTime in '"${startTimes[@]}"'
+ endTime=310
+ filenameTarget=/tmp/P119C2.csv
+ cat /home/masi/Documents/CSV/Case/P119C2T300-310.csv

操作系统:Debian 8.5
Linux 内核:4.6

答案1

[[ -f $lastFile ]]真实的如果文件存在。那么自从你达到cat $dir"P"$id"C"$channel"T"*".csv" 这条路确实如此不是存在。你可能想要if ! [[ -f $lastFile ]]

还,使用更多报价™正确地 - 你应该引用变量。引用静态字符串是一个很好的保护措施,但并不是真正必要的。通常建议编写“最后”行是cat "${dir}P${id}C${channel}T"*'.csv' > "$filenameTarget".

相关内容