Home > Software design >  How to get bash's `cat` program to handle [No such file or directory] edge cases?
How to get bash's `cat` program to handle [No such file or directory] edge cases?

Time:03-23

With mv or rm I would use the -f flag but I'm sure how to handle this for cat.

Is there a way to do this? An alternative that can handle this edge case? or a single line try/except that can handle this edge case?

e.g.,

cat path/to/potential_files/*.fa > output.fa

cat: 'path/to/potential_files/*.fa': No such file or directory

CodePudding user response:

You can use globbing to iterate through all the files that match .fa and append to the outout file using >>:

for file in "$YOUR_PATH/*.fa"; do
    cat "$file" >> outout_file.txt
done

CodePudding user response:

You can write a try ... catch ... with

cat file 2>/dev/null ||
  { 
    echo 'Catch block, only reached when $? -ne 0'
    echo 'Another catch statement'
  }
# Or oneliner (note the spaces around the curly braces and the semicolons)
cat file 2>/dev/null || { echo 'Something '; echo 'else'; }
  • Related