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!
In order to check if a file exists in Bash, you have to use the “-f” option (for file) and specify the file that you want to check. For example, let's say that you want to check if the file “/etc/passwd” exists on your filesystem or not. In a script, you would write the following if statement.
Use the ls Command to List Directories in Bash. We use the ls command to list items in the current directory in Bash. However, we can use */ to print directories only since all directories finish in a / with the -d option to assure that only the directories' names are displayed rather than their contents.
$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With