0

I want to write a shell script that will loop through all the files in a directory and do echo "put ${filename}". How to use a while loop for this logic.

cornuz
  • 2,678
  • 18
  • 35
  • 1
    Break this down in steps and try to figure them out one at a time (they are all already answered on StackOverflow and many other resources) : 1) how do I obtain a list of filenames from the shell prompt? 2) How can I use this list from a script and possibly store it into a variable? 3) what is the syntax for a loop over such a list? – cornuz Oct 26 '20 at 13:40
  • Yes, I can able to get the results for 1 and 2. But, for looping over list how can we use while loop for this.( In regular, we can use for loop). I use this while logic in pipes. Input a single file into pipe is working. But doing it with Directory files, it's not taking. – sat.learner Oct 27 '20 at 14:49
  • `echo ${LIST} | while read filename; do echo "put ${filename}"; done`, with `${LIST}` containing one filename per row. – cornuz Oct 27 '20 at 15:53
  • filename=*.sh; i=0;arr=();for files in $filename;do arr[i]=$files; (( i++ )); done; index=0;while [ $index -lt $i ] do echo "${arr[$index]}";(( index++ )); done – sat.learner Oct 30 '20 at 14:41

1 Answers1

0

You can get the list of all the files in a directory by using the find command and convert it in an array using the round brackets. Finally loop through the array and print it.

path=some_path
files=( $(find $path -maxdepth 1 -type f) )

for file in "${files[@]}"; do
do
  echo "put $file"
done
Shounak
  • 136
  • 1
  • 12