【问题标题】:Prompt user to select a directory with a bash script and read result提示用户选择带有 bash 脚本的目录并读取结果
【发布时间】:2010-07-08 02:07:00
【问题描述】:

我想通过 bash 脚本读取目录(实际上我正在使用 zsh)。

我想列出同一目录中的当前文件夹并将其显示给用户,要求他们输入一个数字以选择正确的文件夹。

Please select a Folder eg, 1,2,3.
1. Folder Name 1 (this should the actual name of the folder in the dir
2. Folder 2
3. Folder 3.

我还希望能够转换输入,例如 1. 回到实际的文件夹名称,这样我就可以了

cd ./$foldername/

感谢您的帮助。 干杯,约翰。

【问题讨论】:

    标签: bash macos shell


    【解决方案1】:

    除非您的格式要求非常严格,否则您可能只使用 bashselect construct

    以下代码将显示当前目录中所有目录的菜单,然后 chdir 到选定的目录:

    #!/bin/bash
    printf "Please select folder:\n"
    select d in */; do test -n "$d" && break; echo ">>> Invalid Selection"; done
    cd "$d" && pwd
    

    【讨论】:

    • 太棒了。测试和工作就像一个魅力。谢谢!这正是我想要的方式。干杯,约翰。
    【解决方案2】:
    #!/bin/bash
    
    dirs=(*/)
    
    read -p "$(
            f=0
            for dirname in "${dirs[@]}" ; do
                    echo "$((++f)): $dirname"
            done
    
            echo -ne 'Please select a directory > '
    )" selection
    
    selected_dir="${dirs[$((selection-1))]}"
    
    echo "You selected '$selected_dir'"
    

    【讨论】:

    • 感谢为我工作。如果要使用变量中的目录:dirs=( "$dir"/"$prd"/* ); 或以某个名称开头的目录 dirs=( "$dir"/"$prd"/["$src"]* );
    【解决方案3】:

    看到了这个 sn-p @ some stack link 不知道确切..虽然可能有用

     #! /bin/bash
    
    # customize with your own.
    options=(backup_*/)
    
    menu() {
        clear
        echo "Avaliable options:"
        for i in ${!options[@]}; do 
            printf "%3d%s) %s\n" $((i+1)) "${choices[i]:- }" "${options[i]}"
        done
        [[ "$msg" ]] && echo "$msg"; :
    }
    
    prompt="Check an option (again to uncheck, ENTER when done): "
    while menu && read -rp "$prompt" num && [[ "$num" ]]; do
        [[ "$num" != *[![:digit:]]* ]] && (( num > 0 && num <= ${#options[@]} )) || {
            msg="Invalid option: $num"; continue
        }
        ((num--)); msg="${options[num]} was ${choices[num]:+un}checked"
        [[ "${choices[num]}" ]] && choices[num]="" || choices[num]="[+]"
    done
    
    printf "You selected"; msg=" nothing"
    for i in ${!options[@]}; do 
        [[ "${choices[i]}" ]] && { printf " %s" "${options[i]}"; msg=""; }
    done
    echo "$msg"
    

    【讨论】:

      猜你喜欢
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 2016-04-18
      • 2018-01-07
      • 2020-09-04
      • 1970-01-01
      • 2021-05-09
      • 1970-01-01
      相关资源
      最近更新 更多