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

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

我想用bash脚本读取dir(实际上我使用的是zsh)。

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

1
2
3
4
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.

我也希望能够转换输入eg 1。回到实际的文件夹名,这样我可以

1
cd ./$foldername/

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


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

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

1
2
3
4
printf"Please select folder:
"

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


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/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'"


看到这个片段@some stack link dunno正是..尽管可能有用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 #! /bin/bash

# customize with your own.
options=(backup_*/)

menu() {
    clear
    echo"Avaliable options:"
    for i in ${!options[@]}; do
        printf"%3d%s) %s
"
$((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"