How do you copy something to the clipboard when running a script triggered by incron?

I've got a script that works perfectly when I run it as myself on the command line but when the script is run by incron the line that copies a value to the clipboard doesn't work. Basically I'm using incron to monitor the addition of a new file in a particular directory then upload that file to an FTP server and copy the URL to the clipboard. This is the line that fails (seemingly does nothing) when the script is run by incron:

echo -n $URL | xclip -selection clipboard

My guess is that incron doesn't have access to the clipboard in the same way that I do as a logged in user, but I don't know what to do about it. Any help would be awesome.

3

1 Answer

xclip is an application that needs environment variables such as $XAUTHORITY and $DISPLAY to talk to the X11-server. You can create a cronjob the looks as follows:

/bin/su your_username -c "export XAUTHORITY='/home/your_username/.Xauthority'; export DISPLAY='$(strings /proc/$(pgrep -n Xorg)/environ | awk -F== '$1 ~ "DISPLAY"{print $2}')'; echo -n "message" | xclip -selection clipboard"

Use your own username instead of your_username. It is a long line, but cron doesn't accept multiple lines as cronjob entries. However, here is what it does:

  • /bin/su your_username: it switches the user
  • -c "...": and runs the command in the quotes
  • export XAUTHORITY='...';: first we need the $XAUTHORITY variable
  • export DISPLAY='...': and the $DISPLAY variable, this is mostly :0, but if not, we can get the variable from the environment of the Xorg process
  • echo ... | xclip ...: finally run the desired command within that environment. No need to use absolute paths anymore because we have a minimal environment now.
4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like