I'm trying to write a shell script which finds all the .zip files in a given directory then lists them on the screen and prompts the user to select one by entering a number e.g.
The available files are:
HaveANiceDay.zip
LinuxHelp.zip
Arrays.zip
Please enter the number of the
archive you would like to select:
What I want to do is store the results of the find command in an array so once the user enters '3' for examaple, I can get the filename by looking up the 3rd array element.
I'm not sure of the syntax for arrays in shell scripts but I want something like this:
array=$(find command)
i=1
while $i -le (array elements)
do
echo "$arrayelement '. ' $arrayelementvalue"
i + 1
done
echo "Please enter the number of the "
echo "archive you would like to select:"
read x
file=arrayvalue(array element $x)
---------- Post updated at 08:52 AM ---------- Previous update was at 08:48 AM ----------
If so, this uses GNU extention -print0 so it works with filenames containing even newlines safely.
#!/bin/bash
while IFS= read -rd '' file; do
zipfiles+=( "$file" )
done < <(find . -name '*.zip' -print0)
for e in "${!zipfiles[@]}"; do
echo "$e) ${zipfiles[e]}"
done
Thanks for the reply. I'm using Linux shell script so I'll give this a try when I get home.
Please could you explain what each step is doing? I'm new to Linux and shell script so I'd like to learn and understand exactly what each bit is doing rather than just copying and pasting someone elses code.
Thanks.
PS3="Your choice (ENTER=list again, e=end):"
select f in *.zip
do
[ "$REPLY" = "e" ] && break
echo "Choice: ($REPLY) $f"
echo $f
# if like to exit after 1st selection, then add line break
# break
done