Question: I need to write a script which writes to a file how many times this script has been executed.

How can I do that?

Answer: 
I assume you want to have a single file `countfile` that only contains one single number representing the execution counter.

You can read this counter into a shell variable `$counter` e.g. using one of these lines:

* ```
read counter < countfile

```
* ```
counter=$(cat countfile)

```

Simple integer additions can be done in Bash itself using the `$(( EXPRESSION ))` syntax. Then simply write the result back to our `countfile`:

```
echo "$(( counter + 1 ))" > countfile

```

You should probably also safeguard your script for the case that `countfile` doesn't exist yet and create one initialized with the value 1 then.

The whole thing might look like this:

```
#!/bin/bash
if [[ -f countfile ]] ; then
    read counter < countfile
else
    counter=0
fi
echo "$(( counter + 1 ))" > countfile

```
This solution uses the same approach as [Byte Commander’s answer](/a/988035/175814) but it doesn't rely on shell arithmetic or other Bashisms.

```
exec 2>&3 2>/dev/null
read counter < counter.txt || counter=0
exec 3>&2 3>&-
expr "$counter" + 1 > counter.txt

```

The stream redirections

1. duplicate the standard error stream (2) to a different file descriptor (3),
2. replace it (2) with a redirection to `/dev/null` (to suppress the error message in the subsequent redirection of the input of the `read` command if the counter file is missing expectedly),
3. later duplicate the original standard error stream (now at 3) back into place (2) and
4. close the copy of the standard error stream (3).