Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to increment with find -exec?

Tags:

I Would like to do something like that

#!/bin/bash

nb=$(find . -type f -name '*.mp4' | wc -l)
var=0
find . -type f -name '*.mp4' -exec ((var++)) \;
echo $var

But it doesn't work ? Can you help me ?

like image 511
romainlavisse Avatar asked Sep 25 '17 19:09

romainlavisse


1 Answers

You can't. Each exec is performed in a separate process. Those processes aren't part of your shell, so they can't access or change shell variables. (They could potentially read environment variables, but updated versions of those variables would be lost as soon as the processes exited; they couldn't make changes).

If you want to modify shell state, you need to do that in the shell itself. Thus:

#!/usr/bin/env bash
#              ^^^^- NOT /bin/sh; do not run as "sh scriptname"

while IFS= read -r -d '' filename; do
  ((++var))
done < <(find . -type f -name '*.mp4' -print0)

Note preincrement vs postincrement -- that helps you avoid some gotchas if you're running your script with set -e (though I'd argue that the better practice is to avoid that "feature").

See Using Find for details.

like image 107
Charles Duffy Avatar answered Sep 25 '22 03:09

Charles Duffy