Home > Software design >  Check if shell script is already running (feh) (i3)
Check if shell script is already running (feh) (i3)

Time:09-13

Inside my ~/Pictures/wallpapers/ folder I have a shell script that changes the wallpaper using a while true each time the sleep function terminates:

feh-auto.sh

#!/bin/bash
while true; do
  feh /home/maruko/Pictures/wallpapers --randomize --bg-fill
  sleep 1800
done

this script is automatically run each time the laptop powers up, or the i3 configuration is reloaded in place using the shortcut Win Shift R:

~/.config/i3/config

...
### CHANGE WALLPAPER RANDOMLY
# https://www.linuxandubuntu.com/home/set-background-wallpapers-on-i3wm
exec_always --no-startup-id ~/Pictures/wallpapers/feh-auto.sh
...

Making changes to the i3 configuration is usually accompanied with a reload in place, so that said changes take place.

The problem is that each time a reload occurs, a new instance of feh-auto.sh is also created, meaning that now instead of 1 timer, I have multiple timers of 1800, that will change the wallpaper x times where x is the number of times I reloaded the configuration.

I would like a more appropriate behavior as I reload: check if feh-auto.sh is already running and if it is, do not create a new instance.

Could you please guide me to the best solution?

Thank you.


EDIT

As @balki suggested in the comments, I have created a cron job

(sudo crontab -e)

@reboot /home/maruko/Documents/program-files/shell/feh-auto.sh

to run the following script

feh-auto.sh

#!/bin/bash

export DISPLAY=0:0
feh /home/maruko/Pictures/wallpapers/ --randomize --bg-fill

However, when booting up or rebooting the system, the wallpaper is blank as if nothing really happened. The command sudo systemctl status cronie.service reports the following:

crond[3300]: pam_unix(crond:session): session opened for user root(uid=0) by (uid=0)
CROND[3307]: (root) CMD (/home/maruko/Documents/program-files/shell/feh-auto.sh)
CROND[3300]: (root) CMDOUT (feh ERROR: Can't open X display. It *is* running, yeah?)
CROND[3300]: (root) CMDEND (/home/maruko/Documents/program-files/shell/feh-auto.sh)
CROND[3300]: pam_unix(crond:session): session closed for user root

I don't know what to do next.

CodePudding user response:

The answer to this post is to read documentation:

i3 config comes with the exec and exec_always commands:

exec will execute the command once at boot,

exec_always will execute the command on reloads too.

The solution is to substitute the above call to feh-auto.sh:

~/.config/i3/config

### START FEH WALLPAPER
# note: exec_always will run the script on each reload, not ideal
# --no-startup-id will eliminate the problem of loading icon on boot
exec --no-startup-id /home/maruko/Pictures/wallpapers/feh-auto.sh
  • Related