简体   繁体   English

在目录中查找文件夹,然后将其作为bash脚本中的选项列出

[英]Find folders in a directory, then list them as options in bash script

I am writing a script in order to perform a series of operations with the development sites I have in my local machine. 我正在编写脚本,以便对本地计算机上的开发站点执行一系列操作。 The idea is to list all folders (websites) in "/var/www/" and let the user choose one to perform subsequent operations. 这个想法是在“ / var / www /”中列出所有文件夹(网站),并让用户选择一个文件夹来执行后续操作。 I found some inspiration for this script here . 我在这里找到了此脚本的灵感。

I am just beginning to learn bash, so do expect profanities in the code: 我刚刚开始学习bash,因此请期待代码中的亵渎行为:

This is where I am stuck: 这就是我被困的地方:

#!/bin/bash

cd /var/www
options=( $(find . -maxdepth 1 -type d -printf '%P\n') )
options[$[${#options[@]}+1]]="type a new site"

title="Website developing script"
prompt="Choose the site:"

echo "$title"
PS3="$prompt "
select opt in "${options[@]}" "Quit"; do 

    case "$REPLY" in
        # so far so good, all folders are properly listed as options            

        # the answer, I guess, is placing a loop here in order to change this
        # example line into a list of options, but I can't figure out how
        1 ) echo "You picked $opt which is option $REPLY";;    

    $(( ${#options[@]}+1 )) ) echo "Exiting"; break;;
    *) echo "Invalid option. Try another one.";continue;;

    esac

done

Any hints are most welcome. 任何提示都是最欢迎的。 Thanks in advance. 提前致谢。

Define function(s) to handle each case. 定义处理每种情况的功能。 Instead of those echo statements in switch cases, call the appropriate functions with all required arguments. 在切换情况下,不要使用那些echo语句,而是使用所有必需的参数来调用适当的函数。

I would suggest cases to handle "Quit" and "Type a new site" and a general case for performing all the actions on any selected directory. 我建议处理“退出”和“键入新站点”的案例,以及对任何选定目录执行所有操作的一般案例。

The following is slightly hackish. 以下是一些小技巧。

Untested. 未经测试。

#!/bin/bash

cd /var/www
options=( $(find . -maxdepth 1 -type d -printf '%P\n') )
lastdirindex=${#options[@]}

saveIFS=$IFS
IFS='|'
pattern="^(${options[*]})$" # create a regex that looks like: ^(dir1|dir2|dir3)$
IFS=$saveIFS

options+=("type a new site")
newindex=${#options[@]}
options+=("Quit")
quitindex=${#options[@]}

processchoice () { echo "Do stuff with choice $1 here"; }

title="Website developing script"
prompt="Choose the site:"

echo "$title"
PS3="$prompt "

select opt in "${options[@]}"; do 
    case $([[ $REPLY =~ $pattern ]] && echo 1 || echo "$REPLY") in
        1          )  echo "You picked $opt which is option $REPLY"; processchoice "$REPLY";;
        $newindex  )  read -r -p "Enter a new site" newsite; processchoice "$newsite";;
        $quitindex )  echo "Exiting"; break;;
        *          )  echo "Invalid option. Try another one."; continue;;
    esac
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM