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

时间:2010-07-08 02:07:00

标签: bash macos shell

我想用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/

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

3 个答案:

答案 0 :(得分:24)

除非您的格式要求非常严格,否则您可以使用 bash select construct

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

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

答案 1 :(得分:4)

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

答案 2 :(得分:1)

看到这个片段@某些堆栈链接dunno确切......虽然可能有用

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