提示用户从一组文件夹中选择所需的文件夹

时间:2017-01-13 07:17:40

标签: bash

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

Please select a Folder eg, 1,2,3.
1. Folder Name 1 
2. Folder 2
3. Folder 3.

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

cd ./$foldername/

我试过但不成功

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

抛出错误“select:not found” 为什么会这样?我哪里错了?

1 个答案:

答案 0 :(得分:0)

这就像你之后的那样吗?

#put directories into an array
folder_list=($(find /$foldername/* -maxdepth 0 -type d -exec basename {} \;))
#loop the output to prevent errors in the user's input
while true; do
    #clear the screen for each loop iteration
    tput clear
    #print the contents of the array and number them
    printf '%s\n' "${folder_list[@]}" | cat -n
    #read user input and store response as variable
    read -p $'Please select a Folder eg, 1,2,3.\n>' REPLY
    #check if variable is zero or not a number, if so restart the loop
    #check if variable is within the range of array content
    if ((REPLY)) && ((REPLY<=${#folder_list[@]})); then
        #if it is then print it out and break the loop
        echo ${folder_list[$((--REPLY))]}
        break
    fi
    echo "Invalid response"
done

值得指出的是,由于双括号,此方法不可移植。

对所有编辑感到抱歉,代码对我来说效率不高。