17

I am trying to use the files in a directory as options in a bash script. The user should be able to select one and then pass the name of the selected file into a variable. So far I can get the list of files, but after a few hours trying I can't figure out how to show them as options.

#!/bin/bash prompt="Please select a file:" options=( $(find -maxdepth 1 -print0 | xargs -0) ) PS3="$prompt " select opt in "${options[@]}" "Quit"; do case "$REPLY" in for i in "${options[@]}" do $i' ) echo "You picked $opt which is file $REPLY";;' done $(( ${#options[@]}+1 )) ) echo "Goodbye!"; break;; *) echo "Invalid option. Try another one.";continue;; esac done 

Any help is much appreciated. Thanks!

2 Answers 2

25

I do not think case is suitable here:

#!/bin/bash prompt="Please select a file:" options=( $(find -maxdepth 1 -print0 | xargs -0) ) PS3="$prompt " select opt in "${options[@]}" "Quit" ; do if (( REPLY == 1 + ${#options[@]} )) ; then exit elif (( REPLY > 0 && REPLY <= ${#options[@]} )) ; then echo "You picked $opt which is file $REPLY" break else echo "Invalid option. Try another one." fi done ls -ld "$opt" 
Sign up to request clarification or add additional context in comments.

2 Comments

I am getting an error using the above code. /home/RepLoqt # sh -x RevPrxyLogQuery.sh ' title='Reverse Proxy Log Query Tool (RepLoqt) ' prompt='Select the log file you want to query: ++ find ./logfiles -maxdepth 1 -print0 ++ xargs -0 + options='(./logfiles ./logfiles/log_18-44 ./logfiles/log_18-3) ' $'\r''Reverse Proxy Log Query Tool (RepLoqt) everse Proxy Log Query Tool (RepLoqt) ' PS3='Select the log file you want to query: 'evPrxyLogQuery.sh: line 7: syntax error near unexpected token ` 'evPrxyLogQuery.sh: line 7: `select opt in "${options[@]}" "Quit" ;
Never mind, for, some reason, because I had the .sh extension on the end of the file, it was giving me that error. Once I removed the extension, it worked... I'm not sure why.
0

Don't miss percol, fzy, smenu and friends. They'll happily take from stdin, present a user-friendly select menu with interactive filter, then pipe selected lines out again.

1 Comment

I feel like this answer could be greatly improved by giving more detail about each of the proposed alternatives and how each might be used to solve the asker's question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.