-1

I'm using kshon an HP-UX box.

In a portion of my script, I want to list certain files (*.xml), have them numbered and have the user choose a file by typing the number and hitting enter. That filename will then be stored as a variable.

Example of output:

Please choose a file:   
1) bar27.xml      
2) foo1.xml    
3) foobar4.xml  

Then the user types in 1, 2, or 3 and hit enter. The file name chosen needs to be stored as a variable. So if the user chooses 2 the variable should contain foo1.xml.

2
  • 3
    You need to look up the select built-in. It's designed to support that. Note that a web-based search may be trickier; select has lots of meanings. Searching with 'ksh select' gets on -topic results for me, including Linux script select menu. Commented Aug 24, 2016 at 14:10
  • 1
    If you still have trouble after that, update your Q with your best attempt to use select and leave a comment that you have updated your Q. If you get it working either post your Answer (you can accept your own answer after 48 hrs to gain valuable reputation points) or delete this Q. Good luck. Commented Aug 24, 2016 at 14:53

1 Answer 1

2

I've come up with the following which works:

files=$(ls *.xml)
i=1

for j in $files
do
echo "$i) $j"
file[i]=$j
i=$(( i + 1 ))
done

echo "Choose an XML file from above to use:"
read v_CHOOSELIST
echo "File chosen: ${file[$v_CHOOSELIST]}"
Sign up to request clarification or add additional context in comments.

3 Comments

Good shot. Even better: Try someting with select (search on stackoverflow.com/search?q=select+menu+bash ) and update the question when your stuck.
some comments: your script will not work as expected if a filename contains whitespace. Don't parse ls and use a real array files=( *.xml ). Then for i in "${!files[@]}"; do echo "$i) ${files[i]}"; done
but select is way easier: PS3="Choose an XML file from above to use:"; select file in *.xml; do if [ -n "$file" ]; then break; fi; done; echo "you chose $file"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.