為什麼這個表達式在 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".

相關內容