0

I have a simple bash script that checks if a program is running and actions accordingly.

#!/bin/bash

check_running=$(pgrep -x redshift)

if [[ -n "$check_running" ]]; then
    echo "1"
    else
        echo "0"
fi

If I execute the script normally (./script) then it will always return 1. But if I use "bash -x script" then it returns the correct outcome

❯ bash -x redshift
++ pgrep -x redshift
+ check_running=
+ [[ -n '' ]]
+ echo 0
0

I have a similar script checking if openvpn is running and it returns the correct value via regular execution.

Here it is in full:

~/.config/polybar/scripts
❯ pgrep -x redshift

~/.config/polybar/scripts
❯ ./redshift       
1

~/.config/polybar/scripts
❯ bash -x redshift 
++ pgrep -x redshift
+ check_running=
+ [[ -n '' ]]
+ echo 0
0

What am I doing wrong?

1

When you run ./redscript, pgrep -x redscript will match that script's process, so check_running will have a PID. You can put a set -x in the script, or use #! /bin/bash -x as the shebang, to verify this.

  • Isn't that what the -x flag in pgrep is used for? – Ryan Jan 29 '18 at 6:56
  • For a script started as ./redshift, the complete command line is just redshift. pgrep -x redshift will match that. – muru Jan 29 '18 at 7:04
  • psgrep -x find matching for the whole line; while ./redshift and bash -x redshift are one same thing in some logical way, they are two different things in term of psgrep -x. – Bach Lien Jan 29 '18 at 7:35
  • 2
    Of course it will, that makes sense now. The check script is called redshift and the program in /usr/bin is called redshift. Probably a bad idea to do in general.. – Ryan Jan 29 '18 at 7:39

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.