我想遍歷存盤在其中的檔案名陣列,files_arr以在 POSIX shell 中創建基于終端的檔案管理器。
函式的簡化版本list_directory如下所示:
# Presents the user with the files in the directory
list_directory() {
# Iterate over each element in array `files_arr` by index, not by filename!
# And outputs the file name one on each line
for file in "${!files_arr[@]}"; do
echo "${files_arr[file]}"
done
}
我想實作一種n從陣列中排除第一個檔案的方法files_arr。
n 由用戶滾動超過當前終端視窗大小以創建滾動檔案效果的頻率定義,突出顯示游標當前所在的檔案。
在如下所示的目錄(例如主目錄)上:

為了實作這一點,我嘗試創建一個類似 C 的 for 回圈,如下所示:
for ((file=$first_file; file<=${!files_arr[@]}; file=$((file 1))); do
或作為整個功能:
# Presents the user with the files in the directory
list_directory() {
# Iterate over each element in array `files_arr` by index, not by filename!
#for file in "${!files_arr[@]}"; do
for ((file=$first_file; file<=${!files_arr[@]}; file=$((file 1))); do
# Highlighted file is echoed with background color
if [ $file -eq $highlight_index ]; then
echo "${BG_BLUE}${files_arr[file]}${BG_NC}"
# Colorize output based on filetype (directory, executable,...)
else
if [ -d "${files_arr[file]}" ]; then
echo "$FG_DIRECTORY${files_arr[file]}$FG_NC"
elif [ -x "${files_arr[file]}" ]; then
echo "$FG_EXECUTABLE${files_arr[file]}$FG_NC"
else
echo "${files_arr[file]}"
fi
fi
# $LINES is the terminal height (e.g. 23 lines)
if [ "$file" = "$LINES"]; then
break
fi
done
}
回傳錯誤:
./scroll.sh: line 137: syntax error near `;'
./scroll.sh: line 137: ` for ((file=$first_file; $file<=${!files_arr[@]}; file=$((file 1))); do'
如何遍歷陣列files_arr,定義 的起始索引$file?
uj5u.com熱心網友回復:
您可以使用以下命令遍歷陣列:
for (( i = $first_file; i < ${#files_arr[@]}; i )); do
echo ${files_arr[i]}
done
但使用起來似乎更干凈:
for file in ${files_arr[@]:$first_file}; do
echo "$file"
done
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/382629.html
