【发布时间】:2022-01-18 16:34:54
【问题描述】:
我想遍历存储在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
}
我想实现一种从数组files_arr 中排除第一个n 文件的方法。
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 的起始索引?
【问题讨论】:
标签: shell for-loop variables unix posix