Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you store a list of directories into an array in Bash (and then print them out)?

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! 
like image 966
qodeninja Avatar asked Dec 20 '10 21:12

qodeninja


People also ask

How do I print an array in Bash?

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.

How do I list all directories in Bash?

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.

Are there arrays in Bash?

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.


1 Answers

$ 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/! 
like image 59
Dennis Williamson Avatar answered Oct 24 '22 09:10

Dennis Williamson