【问题标题】:shell - How to define a variable in a C-type for loop?shell - 如何在 C 类型的 for 循环中定义变量?
【发布时间】: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


    【解决方案1】:

    您可以使用以下方法遍历数组:

    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
    

    【讨论】:

    • 非常感谢!我什至尝试使用 :$first_file 但它没有以某种方式解决。我刚刚在我的代码的另一部分发现了一个错误,所以我现在需要修复它!再次非常感谢!祝你有美好的一天!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 2011-12-05
    • 2020-03-05
    相关资源
    最近更新 更多