2

I am trying to make a script that will toggle redshift (a night mode application). So, I've done this,

#!/bin/bash

pgrep redshift > /dev/null && \ 
         killall redshift || \
         setsid redshift [options] &> /dev/null

This looks up for the program and if that program is running in the background then it is killed otherwise it is started and is setsid. Now, this script works if I am to kill the process, but this script hangs when I run it back.

  • What am I doing wrong?
  • Is there other ways to put the process background so that killing the terminal won't stop the program?
  • 2
    I think you could simplify slightly by using just pgrep redshift > /dev/null && ... – Jeff Schaller Jun 14 '19 at 16:47
3

When you invoke the program with bash, bash interprets &> as a special redirection operator (redirect both stdout and stderr), and not as you may have intended: a background operator & and a stdout redirection >. Separate the two tokens and you'll get the background behavior you're expecting:

#!/bin/bash

pgrep redshift > /dev/null && 
  killall redshift || 
    setsid redshift [options] & > /dev/null

Consider being kinder to your future self and expand the logic slightly; you want to kill redshift if it's there, then start it with some options:

if pgrep redshift > /dev/null
then
  pkill redshift
fi
setsid redshift options & > /dev/null 
|improve this answer|||||
3

redshift has a toggle feature

Send signal SIGUSR1 to the redshift process to toggle:

pkill -USR1 redshift

It is documented on their website, but not in the software’s documentation. I had opened a pull request to document this feature in its man page.

|improve this answer|||||

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.