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

时间:2012-06-25 15:57:55

标签: arrays bash

我正在编写一个脚本,以便对我在本地计算机上的开发站点执行一系列操作。我们的想法是列出“/ var / www /”中的所有文件夹(网站),让用户选择一个来执行后续操作。我找到了这个脚本的一些灵感here

我刚刚开始学习bash,所以请注意代码中的亵渎:

这是我被困的地方:

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

任何提示都是最受欢迎的。提前谢谢。

2 个答案:

答案 0 :(得分:0)

定义处理每个案例的函数。而不是在switch case中使用echo语句,而是使用所有必需参数调用相应的函数。

答案 1 :(得分:0)

我建议处理“退出”和“键入新网站”的案例以及在任何选定目录上执行所有操作的一般情况。

以下是有点hackish。

未测试。

#!/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
相关问题