0

I'm trying to loop over files in a directory given as an argument for a script in bash.

#!/bin/bash

directory=$1

for file in $(find "$directory" -type f 2>/dev/null)
do
     echo "$file"
done

when running the script:

./script_name directory_name

nothing happens.

Many thanks in advance.

caman177
  • 1
  • 1
  • `find "$directory" -type f` – Jetchisel Feb 08 '23 at 17:00
  • 1
    Note [BashPitfalls #1](https://mywiki.wooledge.org/BashPitfalls#for_f_in_.24.28ls_.2A.mp3.29). `for item in $(anything)` is itself bad practice, even after you've fixed the above. – Charles Duffy Feb 08 '23 at 17:01
  • Apologies, your suggestion is how I've actually written the script. I'll edit the post to reflect that. Unfortunately it still produces no output. – caman177 Feb 08 '23 at 17:03
  • @CharlesDuffy I understand. I'm new to shell scripting, just trying to understand the fundamentals. – caman177 Feb 08 '23 at 17:05
  • 1
    The _Complex Actions_ section of [Using Find](https://mywiki.wooledge.org/UsingFind) is a good place to start re: using `find` correctly; but with your code as-edited, it _should_ actually work. If you take out the `2>/dev/null` are any error messages printed? – Charles Duffy Feb 08 '23 at 17:08
  • 1
    (In general, `2>/dev/null` should only be used when you have a _very_ good reason why: hiding problems from yourself is a good way to not know why things are failing when they do; and taking redirections that hide stderr _out_ is the very first thing you should do when you have issues, _before_ asking questions here). – Charles Duffy Feb 08 '23 at 17:08
  • 1
    Think about `for file in "$directory"/*; do echo "$file"; done`, alternately, so you don't need `find` at all. Or, if you want to keep `find` for some reason, add `-maxdepth 1` to stop it from recursing into subdirectories, and also apply the advice in the Using Find page linked above to iterate over results in a way that works for unexpected filenames (those with spaces, globs, etc etc). – Charles Duffy Feb 08 '23 at 17:12

0 Answers0