I have a bash file that does a global update to files with a given name. I have used this script for several decades without any problems. I became curious as to how many files were being updated and added a var that was incremented after each update. However, even though it is updating files the var "CNT" always reports no files where updated.
I am using the suggested "inc" from this website. What am I doing wrong?
Thanks for the help :-)
#!/usr/bin/bash
SEARCH=test.txt # file name to search for
SOURCE=test.txt # file name to replace it
CNT=0; # number of files updated
find ./ -name "$SEARCH" | while read f; do
cp "$SOURCE" "$f" > /dev/null 2>&1; # copy and don't show errors
((CNT=CNT+1))
done; # end of while
echo -en "\n"
echo -en "$CNT files where replaced.\n"
I also tried using this as suggested but did not find any difference regardless of inserting an "inc" or "wc" (word count) in various syntax.
shopt -s lastpipe
find . -name "$search" -type f -exec 'bash
for f; do
cp "$f" "$source"
done' sh {} +
Based on the link provided by Kamil Maciorowski (below), sub-shells are being created within the "find". Perhaps a better question is "How can I count the number of times find loops?"
Solution: Adding "shopt -s lastpipe" fixed the first script but the suggested 2nd script still did not work with "shopt -s lastpipe".
find … | while read …is not the most robust solution,find … -exec …is almost always the right way. At least useIFS= read -r …. – Kamil Maciorowski Jun 30 '23 at 20:03find". Everything butfind ./ -name whatever-$SEARCH-expands-tois outside offind. – Kamil Maciorowski Jun 30 '23 at 20:46find: here. In the context of where it says "findperforms tests of our choice and prints tokens" note-exec cp "$SOURCE" {} \;may be a test. Please see Understanding the-execoption offind. – Kamil Maciorowski Jun 30 '23 at 20:53shopt -s lastpipe. Have you tried to run it at the beginning of your script? It should make your counting work. The script will remain kinda flawed, but if you "have used this script for several decades without any problems" then probably it's good enough for you. A sane and easy improvement isIFS= read -rfrom the second link, it will make the script less flawed. – Kamil Maciorowski Jul 01 '23 at 17:47shopt -s lastpipewith your original script. – Kamil Maciorowski Jul 01 '23 at 17:52findloops?". In the former caseshopt -s lastpipeis a solution; the latter case begs for a solution that fixes all the flaws. – Kamil Maciorowski Jul 01 '23 at 18:05