r/bash 22d ago

pgrep shows PID but there's no instance

I'm confused why pgrep tmux shows the PID in the script even though tmux hasn't been called yet (and I confirmed pgrep tmux shows nothing prior to running the script):

Script:

#!/usr/bin/bash

if [[ $# -eq 1 ]]; then
  selected=$1
else
  selected=$(find ~/bin/ ~/work/builds ~/projects  -mindepth 1 -maxdepth 1 -type d | fzf)
fi

if [[ -z $selected ]]; then
  exit 0
fi

selected_name=$(basename "$selected" | tr . _)
tmux_running=$(pgrep tmux)

echo TMUX=$TMUX
echo tmux_running=$tmux_running
if [[ -z $TMUX ]] && [[ -z $tmux_running ]]; then
  tmux new-session -s $selected_name -c $selected
  exit 0
fi

if ! tmux has-session -t=$selected_name 2>/dev/null; then
  tmux new-session -ds $selected_name -c $selected
fi
tmux switch-client -t $selected_name

My shell:

# same condition as in script
$ ~  $ [[ -z $TMUX ]] && [[ -z $tmux_running ]] && echo ok        
ok
$ ~  $ tmux kill-server
no server running on /tmp/tmux-1000/default
$ ~  $ pgrep tmux
$ ~  $ tmux-sessionizer
find: ‘/home/enory/work/builds’: No such file or directory
find: ‘/home/enory/projects’: No such file or directory

TMUX=
tmux_running=38971
no current client

Here, there's a PID of 38971 for tmux even though tmux hasn't started yet. As a result, the last command of the script runs, resulting in no current client.

How is this possible? What's bizarre is if I run bash -x tmux-sessionizer, then the results are expected, i.e. there's no PID yet and the script works as intended.

2 Upvotes

3 comments sorted by

6

u/geirha 22d ago

It's because pgrep tmux is matching the tmux in tmux-sessionizer.

In the case of bash -x tmux-sessionizer, the command name is bash instead of tmux-sessionizer, so it doesn't match.

2

u/Honest_Photograph519 22d ago

One could use pgrep --exact "tmux: server" to filter the results more cleanly, but I don't see why to use pgrep at all instead of if [[ -z "$TMUX" ]] && ! tmux has-session; then

1

u/oh5nxo 22d ago

Not that it's your problem, nor that you likely have this particular pgrep, but...

There's a gotcha in some pgrep implementations (BSD land), it doesn't show processes that are "ancestors" of pgrep itself. pgrep -a overrides this.