code_resources
code_resources

Reputation: 11

Simple Bash script on macos creating unwanted infinite loop

I am trying to run a bash script to concatenate the contents of all text files in a folder/sub-folders and output that to a text file:

#!/bin/bash

find . -type f -name '*.txt' -exec cat {} + >> output.txt

This is creating an infinite loop.

My test directory is set up like: ~/desktop/Dir0/Dir1/Dir2

I created 2 text files:

  1. ~/desktop/Dir0/Dir1$ touch text1.txt && echo "Hello" >> text1.txt
  2. ~/desktop/Dir0/Dir1/Dir2$ touch text2.txt && echo "World" >> text2.txt

and then ran the .sh from within Dir0

The script did not conclude and running cat output.txt listed a long file containing Hello\nWorld\nHello\nWorld\nHello\nWorld... infinitely.

Troubleshooting I have tried so far:

  1. Tried the same script in a Mint vm and it worked fine.
  2. I upgraded bash3.2 to 5.1.16, still looping
  3. Reading/testing

Anyone have an idea what might be happening here?

Upvotes: 1

Views: 141

Answers (1)

James Risner
James Risner

Reputation: 6074

A more efficient way is to use xargs:

find . -type f -name '*.txt' ! -name 'output.txt' -print0 | \
    xargs -0 cat > output.txt
  • This finds all files ending in .txt and not named output.txt.
  • Passes them null (\0) terminated to xargs in null termination mode (-0).
  • Then cat is called with more than 1 argument per execution.
  • Finally writing to the desired output file.

Upvotes: 1

Related Questions