linuxbashlinux-mintxfce

Increment the title of files output by a command in a shell script


I made this simple bash script to take a full-screen screenshot and save it to the pictures folder

#!/usr/bin/bash

xfce4-screenshooter -f -s /home/rgcodes/Pictures/Screenshot_$scrshotcount.png 
let "scrshotcount++"

...which runs into a problem. scrshotcount is a global variable I defined in /etc/environment to be incremented every time the script runs. However, the script fails to increment the variable globally, and causes the script to just overwrite the previous screenshot. Searches on Google and Stack Overflow revealed that the problem isn't straightforward at all (something about child shells being unable to change variables for parents), and finding some other method would be better.

Here's my question. How do we append numbers (in ascending order) to the screenshots the script throws out so that they are saved just like those taken on Windows?(Windows auto-suffixes matching filenames, rather than overwriting them, so all Screenshots have the same name 'Screenshot' and the number of times the screenshot command has been used.)

I am using @erikMD's method as a temporary stop-gap for now.


Solution

  • In addition to the excellent advice about using a date instead of a counter, here's a way to use a counter :/

    dir=$HOME/Pictures
    
    # find the current maximum value
    current_max=$( 
        find "$dir" -name Screenshot_\*.png -print0 \
        | sort -z -V \
        | tail -z -n 1
    )
    if [[ ! $current_max =~ _([0-9]+)\.png ]]; then
        echo "can't find the screenshot with the maximum counter value" >&2
        exit 1
    fi
    
    # increment it
    counter=$(( 1 + ${BASH_REMATCH[1]} ))
    
    # and use it
    xfce4-screenshooter -f -s "$dir/Screenshot_${counter}.png"
    

    You'll have to manually create the Screenshot_1.png file.