Create dynamical from files in directory

Hello

I putting together a menu script for some processing operations and I want to do the following, was googling for some time, but can figure the following out.

Im in a folder lets say /input_files

I want to list the files something like the following, each file is assigned a number, now If I put the corresponding file number to read, I want that the number will point to the file name

#!/bin/bash
clear
#set -x
echo " TEST"
files=$(ls -l | grep ^- |  awk '{print $NF}')
i='0'
for file in $files
do
i=`expr $i + 1`
echo $i")"  $file
done
echo -e "\n Choose file: "
read VARIABLE_WITH_FILE NUMBER
cat $FILE_NAME

 TEST
1) list_menu.sh
2) one
3) test_file
4) two

 Choose file:
If I press number 3, I want the script to cat test_file, when pressing 1, cat list_menu.sh

Thank you

Try something like:

select f in $(ls -p | grep -v /)
do
  cat "$f"
done

This would only work if the are no files with spaces or newlines in the directory which may be OK from the command line..

A more robust solution - using bash arrays - would be:

files=(*)
for ((i=0; i<${#files[@]}; i++))
do
  [ -f "${files}" ] || unset files      # remove directory entries that are not plain files
done

select f in "${files[@]}"; 
do 
  cat "$f"
done
1 Like

Thank you so much that select is awesome,

I think the files can be handled much easier -

ls -l | egrep ^- | egrep -v "*sh" | awk '{print $NF}'

added the PS3 variable + break since after one file I cant to take that value into the next processing.

nevertheless thank you so much

You're welcome. Yes but it has the same problem, that files with spaces or newlines are not handled properly..