Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prompt user to select a directory with a bash script and read result

Tags:

bash

shell

macos

I want to be read a dir with a bash script (actually I am using zsh).

I want to list the current folders in the same dir and display it to the user asking them to enter a number to select the correct folder.

Please select a Folder eg, 1,2,3.
1. Folder Name 1 (this should the actual name of the folder in the dir
2. Folder 2
3. Folder 3.

I would like to also be able to convert the input eg 1. Back to the actual folder name so I can

cd ./$foldername/

Thanks for you help. Cheers, John.

like image 584
John Ballinger Avatar asked Jul 08 '10 02:07

John Ballinger


People also ask

How do I select a directory in bash?

Basic Bash Commandscd path-to-directory : The command followed by a path allows you to change into a specified directory (such as a directory named documents ). cd .. (two dots). The .. means “the parent directory” of your current directory, so you can use cd .. to go back (or up) one directory.

How do you prompt for input from user in Linux shell script?

You can use the built-in read command ; Use the -p option to prompt the user with a question.

Which command can you use to retrieve user inputs into a variable in a bash script?

The linux read command is used to take a user input from the command line. This is useful when we want to provide user interactivity at runtime. We can then use the $ sign in front of the variable name to access its value, e.g. $variable_name .


2 Answers

Unless your formatting requirements are very strict, you can probably just use bash’s select construct.

The following code will present a menu of all the directories in the current directory and then chdir to the selected one:

#!/bin/bash
printf "Please select folder:\n"
select d in */; do test -n "$d" && break; echo ">>> Invalid Selection"; done
cd "$d" && pwd
like image 130
Chris Johnsen Avatar answered Sep 22 '22 05:09

Chris Johnsen


#!/bin/bash

dirs=(*/)

read -p "$(
        f=0
        for dirname in "${dirs[@]}" ; do
                echo "$((++f)): $dirname"
        done

        echo -ne 'Please select a directory > '
)" selection

selected_dir="${dirs[$((selection-1))]}"

echo "You selected '$selected_dir'"
like image 42
amphetamachine Avatar answered Sep 24 '22 05:09

amphetamachine