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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With