相同排列的內容針對水珠是完全有可能的:
#!/bin/bash
# this array has noncontiguous indexes to demonstrate a potential bug in the original code
array=([0]="hello.c" [3]="cruel.txt" [5]="world.c")
glob=$1
for idx in "${!array[@]}"; do
val=${array[$idx]}
if [[ $val = $glob ]]; then
echo "File $val matches glob expression $glob" >&2
else
echo "File $val does not match glob expression $glob; removing" >&2
unset array[$idx]
fi
done
同樣,可以擴大對文件系統內容的水珠,雖然你會首先要清除IFS以避免字符串分裂:
# here, the expectation is that your script would be invoked as: ./yourscript '*.c'
IFS=
for f in $1; do
[[ -e $f || -L $f ]] || { echo "No file matching $f found" >&2; }
echo "Iterating over file $f"
done
這就是說,一般來說,這是極端 unidiomatic,而不是讓你的腳本開始之前調用shell擴展glob,並從參數向量中讀取匹配文件的列表。因此:
# written this way, your script can just be called ./yourscript *.c
for f; do
[[ -e $f || -L $f ]] || { echo "No file matching $f found" >&2; }
echo "Iterating over file $f"
done
'* .c'不是一個有效的正則表達式。你想過濾一個文件列表嗎?看起來你試圖使用的是某種全局模式。 – slugo
是我試着去過濾文件列表 –
你就不能在使用類似的文件循環:'在* .c文件 做 #$文件是文件 做 ' – slugo