shell脚本交互式选择文件

#!/bin/bash

#中间栈
temp_dir=awk -F = '/TEMP/ {print $2}' ./configs/config

# 获取当前目录下的所有文件(不包括隐藏文件和目录)
files=(*)

# 检查是否有文件
if [ ${#files[@]} -eq 0 ]; then
    echo "当前目录下没有文件。"
    exit 1
fi

# 初始化选中的文件数组
selected_files=()

# 当前选中的索引
current_index=0

# 绘制文件列表函数
draw_menu() {
    clear
    for i in "${!files[@]}"; do
        if [ $i -eq $current_index ]; then
            # 当前选中的项
            if [[ " ${selected_files[@]} " =~ " ${files[i]} " ]]; then
                echo -e "\033[32m> \033[31m${files[i]}\033[0m"  # 绿色箭头,红色文本表示选中
            else
                echo -e "\033[32m> \033[0m${files[i]}"  # 绿色箭头
            fi
        else
            if [[ " ${selected_files[@]} " =~ " ${files[i]} " ]]; then
                echo -e "  \033[31m${files[i]}\033[0m"  # 红色文本表示选中
            else
                echo "  ${files[i]}"
            fi
        fi
    done
}
 
IFS='' #修改默认分隔符,不然空格键会被转为回车键
# 主循环
while true; do
    echo '上下键选择文件,空格键选中文件,回车确定文件'
    draw_menu
    read -rsn1 input  # 读取一个字符,不显示在屏幕上
    case $input in
        A)  # 上箭头
            if [ $current_index -gt 0 ]; then
                ((current_index--))
            fi
            ;;
        B)  # 下箭头
            if [ $current_index -lt $[${#files[@]} - 1] ]; then
                ((current_index++))
            fi
            ;;
        ' ')  # 空格键
            is_selected=false
            for file in "${selected_files[@]}"; do
                if [[ "$file"  == "${files[current_index]}" ]]; then
                   is_selected=true
                   break
                fi
            done
            if $is_selected; then
                # 如果文件已被选中,则从 selected_files 数组中移除
                    selected_files=(${selected_files[@]/${files[current_index]}/})
                else
                    # 如果文件未被选中,则将其添加到 selected_files 数组中
                    selected_files+=("${files[current_index]}")
            fi
            ;;
       '')  # 回车键
            break
            ;;
    esac
done

# 处理选中的文件
if [ ${#selected_files[@]} -eq 0 ]; then
    echo "没有选中任何文件。"
else
    echo "你选择了以下文件:"
    for file in "${selected_files[@]}"; do
        echo "$file"     
    done
fi

大概效果就是这样的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值