提示用户选择一个带有 bash 脚本的目录并读取结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3200252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:18:14  来源:igfitidea点击:

Prompt user to select a directory with a bash script and read result

bashmacosshell

提问by John Ballinger

I want to be read a dir with a bash script (actually I am using zsh).

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

I want to list the current folders in the same dir and display it to the user asking them to enter a number to select the correct folder.

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

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.

I would like to also be able to convert the input eg 1. Back to the actual folder name so I can

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

cd ./$foldername/

Thanks for you help. Cheers, John.

谢谢你的帮助。干杯,约翰。

回答by Chris Johnsen

Unless your formatting requirements are very strict, you can probably just use bash's selectconstruct.

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

The following code will present a menu of all the directories in the current directory and then chdir to the selected one:

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

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

回答by amphetamachine

#!/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'"

回答by Ragav

Saw this snippet @ some stack link dunno exactly..though might be useful

看到这个片段@一些堆栈链接不知道到底..虽然可能有用

 #! /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"