问题
Overview:
I would like my KSH script to test for the presence of certain files in a directory, present the user with a list of those files along with a number. The user then chooses the number they want and the relevant value from the array is assigned to a variable.
So far I have the following:
### Create test files in directory ####
touch ABCDEF.jar
touch BCDEFG.jar
touch CDEFGH.jar
touch DEFGHI.jar
touch EFGHIJ.jar
touch FGHIJK.jar
touch GHIJKL.jar
set -A JARS ` ls -1 | grep .jar | cut -d'.' --complement -f2-`
for i in ${JARS[@]}; do echo "Number) $i"; done
This returns the following list from the array:
Number) ABCDEF
Number) BCDEFG
Number) CDEFGH
Number) DEFGHI
Number) EFGHIJ
Number) FGHIJK
Number) GHIJKL
Firstly, I'd like to replace the place holder "Number)" with a function which increases the number in sequence to get something like this:
1) ABCDEF
2) BCDEFG
3) CDEFGH
4) DEFGHI
5) EFGHIJ
6) FGHIJK
7) GHIJKL
I'd then like to have the script read the user input based on the Number the user has chosen, and assign the correct value from the array to a new variable "JAR_ID"
On the face of it, it seems like a simple problem. However, I just can't seem to get my head round how to do this in a logical way.
Any ideas gratefully appreciated!
TIA Huskie.
回答1:
If you don't mind the full filenames in the list then just this will work.
select JAR in *.jar; do
export NEW_PATCHID=$JAR
echo $NEW_PATCHID
REPLY=''
break
done
If you do mind (and the example indicates you might) and you want to drop .jar
(I'm assuming that's what that cut
is for though cut -d. -f1
would seem simpler for that as would awk -F . '{print $1}'
though that is longer) the following works safely.
jars=(*.jar)
select JAR in "${jars[@]%.jar}"; do
export NEW_PATCHID=$JAR
echo $NEW_PATCHID
REPLY=''
break
done
回答2:
Thanks to Etan's poke in the right direction, I was able to do what I needed using the following code:
#!/bin/ksh
type_prompt='Select JAR> '
PS3="${type_prompt}"
select JAR in `ls -1 | grep .jar | cut -d'.' --complement -f2-` QUIT
do
export NEW_PATCHID=$JAR
echo $NEW_PATCHID
REPLY=''
break
done
This is exactly what I needed and works in the way I want. Thanks again Etan
来源:https://stackoverflow.com/questions/26635101/how-to-have-a-user-select-a-value-from-array-and-pass-that-into-a-variable-in-ks