Suppose you want to create a shell script to process a directory, for example, to change the permissions of all files and subdirectories and for this purpose, you want to give a select option for directory so that the user can select a directory from the menu and that directory will get processed. To do this, below I am demonstrating an example to give an option to the user to select a directory to process in Linux.
Linux - Select a Directory to Process Example
The following program will list out all the directories of the root and will assign a number, the user can select a directory by entering a number. The menu will be displayed as shown in the featured image of this article.
#!/bin/bash dirlist="Finished $(for i in /*;do [ -d "$i" ] && echo $i; done)" PS3='Directory to process? ' # Set a useful select prompt until [ "$directory" == "Finished" ]; do printf "%b" "\a\n\nSelect a directory to process:\n" >&2 select directory in $dirlist; do if [ "$directory" == "Finished" ]; then echo "Finished processing directories." break elif [ -n "$directory" ]; then echo "You chose number $REPLY, processing $directory..." # Do something here break else echo "Invalid selection!" fi done done
Output
Select a directory to process: 1) Finished 7) /home 13) /proc 19) /sys 2) /bin 8) /lib 14) /root 20) /tmp 3) /boot 9) /lost+found 15) /run 21) /usr 4) /cdrom 10) /media 16) /sbin 22) /var 5) /dev 11) /mnt 17) /snap 6) /etc 12) /opt 18) /srv Directory to process?