2

I want to make sure node is running when logging in. So in my .bashrc file I have:

pkill node
sleep 1
node server.js &

Of course, that doesn't check if node is running... it simply kills it and starts it up again. Instead I'd like something like this:

node_process = $(pidof node)
if [not_exists node_process]; then
  node server.js &
fi

The problem is the not_exists method doesn't seem to exist :). How do I test the existence of a number or string in Bash and is this the best way to ensure node is up and running upon login?

1

1 Answer 1

7

You can check if a string is empty using -z:

node_process_id=$(pidof node)
if [[ -z $node_process_id ]]; then
    node server.js &
fi

pidof returns nothing if no matching processes are found, so node_process_id would be set to an empty string.

Sign up to request clarification or add additional context in comments.

3 Comments

This seems like exactly what I'm looking for. Can I just move the $(pidof node) inside the if condition? Curious why I need 2 square brackets around the if condition?
The double brackets are just a more friendly bash version of the single brackets. And yes, I think if ! pidof node; then node server.js & fi should work fine.
Thanks a lot, was banging my head to find a clean solution. Works like a charm.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.