I want to write a shell script to show a list of directories entered by a user and then for a user to select one of the directories with an index number based on how many directories there are
I'm thinking this is some kind of array operation, but im not sure how to do this in shell script
example:
> whichdir There are 3 dirs in the current path 1 dir1 2 dir2 3 dir3 which dir do you want? > 3 you selected dir3!
Print Bash Array We can use the keyword 'declare' with a '-p' option to print all the elements of a Bash Array with all the indexes and details. The syntax to print the Bash Array can be defined as: declare -p ARRAY_NAME.
Use the ls Command to List Directories in Bash. We use the ls command to list items in the current directory in Bash. However, we can use */ to print directories only since all directories finish in a / with the -d option to assure that only the directories' names are displayed rather than their contents.
Bash supports one-dimensional numerically indexed and associative arrays types. Numerical arrays are referenced using integers, and associative are referenced using strings. Numerically indexed arrays can be accessed from the end using negative indices, the index of -1 references the last element.
$ ls -a ./ ../ .foo/ bar/ baz qux* $ shopt -s dotglob $ shopt -s nullglob $ array=(*/) $ for dir in "${array[@]}"; do echo "$dir"; done .foo/ bar/ $ for dir in */; do echo "$dir"; done .foo/ bar/ $ PS3="which dir do you want? " $ echo "There are ${#array[@]} dirs in the current path"; \ select dir in "${array[@]}"; do echo "you selected ${dir}"'!'; break; done There are 2 dirs in the current path 1) .foo/ 2) bar/ which dir do you want? 2 you selected bar/!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With