問題描述
BASH:在 for 循環中使用 continue (BASH: Using a continue in a for loop)
由於這是為了工作,我無法展示我的真實示例;但是會用一個虛擬的例子來解釋我的問題。我有一個運行以下命令的 BASH 腳本:
for name in $HOME/data/individual‑*‑lookup; do
$name
done
但是,如果名稱等於某個屬性(例如 John)。我希望 for 循環跳過這個名稱。我嘗試了以下代碼;但它似乎仍然運行所有選項:
#! /bin/bash
for name in $HOME/data/individual‑*‑lookup; do
if ["$name" == "$HOME/data/individual‑john‑lookup"]; then
continue
fi
$filename
done
參考解法
方法 1:
A few issues I fixed in your code:
Line 3, missing quotes around
$HOME
, to prevent the value to be parsed as multiple words, if it contains characters of the$IFS
environment variable. (See: ShellCheck: SC2231):for name in $HOME/data/individual‑*‑lookup; do ^ ^ "$HOME"/data/individual‑*‑lookup
Line 4, missing spaces inside the test brackets:
if ["$name" == "$HOME/data/individual‑john‑lookup"]; then ^ ^
Line 4, mixed single bracket
[ condition ]
POSIX syntax and==
Bash string equality syntaxif ["$name" == "$HOME/data/individual‑john‑lookup"]; then ^ ^^ ^
Line 7, missing double quotes
"
around$filename
$filename ^ ^ "$filename"
Fixed refactored version:
#!/usr/bin/env bash
filename=() # Array of a command with its parameters
for name in "$HOME"/data/individual‑*‑lookup; do
# Continue to next name if file is physically same,
# regardless of path string syntax
[[ $name ‑ef "$HOME/data/individual‑john‑lookup" ]] && continue
filename=(: "$name") # Command and parameters ":" is a dummy for command name
"${filename[@]}" # Run the command with its parameters
done
Test the ‑ef
comparison to check the file is physically the same rather than string equality, so if file path expands with slight syntax differences, it does not matter.
The ‑ef
condition operator is a Bash feature:
FILE1
‑ef
FILE2
True if file1 is a hard link to file2.
Since there is only one statement after the test, the shorter test && command
can be used, in‑place of if test; then; command; fi
The $filename
command call is replaced by a "${filename[@]}"
array for much better flexibility into adding arguments dynamically.
(by LearnerCode、Léa Gris)