First of all, you can't start two servers on the same port. Ultimately it will fail. However, you might not want a late notice of this. For example, if you do this:


# In one terminal
$ cd elasticsearch-6.1.0
$ ./bin/elasticsearch
...
$ curl localhost:9200
...
"version" : {
    "number" : "6.1.0",
...

# In *another* terminal
$ cd elasticsearch-6.2.4
$ ./bin/elasticsearch
...
$ curl localhost:9200
...
"version" : {
    "number" : "6.1.0",
...

In other words, what happened to the elasticsearch-6.2.4/bin/elasticsearch?? It actually started on port :9201. But that's a rather scary thing because as you jump between project in different tabs or you might not notice that you have Elasticsearch running with docker-compose somewhere.

To remedy this I use this curl one-liner:


$ curl -s localhost:9200 > /dev/null && echo "Already running!" && exit || ./bin/elasticsearch

Now if you try to start a server on a used port it will exit early.

To wrap this up in a script, take this:


#!/bin/bash

set -eo pipefail

hostandport=$1
shift
curl -s "$hostandport" >/dev/null && \
  echo "Already running on $hostandport" && \
  exit 1 || exec "$@"

...and make it an executable called unlessalready.sh and now you can do this:


$ unlessalready.sh localhost:9200 ./bin/elasticsearch

Comments

Sascha Welter

But the real problem here is that elasticsearch goes to a different port without asking or giving feedback.

That is pretty braindead behaviour for any kind of server process. When it does that, how are the clients going to guess that this happened? No sane server should do that.

Peter Bengtsson

Yeah, it's really odd. Why would that ever be useful?!

Your email will never ever be published.

Previous:
GeneratorExit - How to clean up after the last yield in Python June 7, 2018 Python
Next:
How to unset aliases set by Oh My Zsh June 14, 2018 Linux, macOS
Related by category:
gg shell completion August 13, 2025 Linux
Bot traffic hitting my blog July 9, 2025 Web development
set -ex - The most useful bash trick of the year August 31, 2014 Linux
brotli_static in Nginx November 8, 2024 Linux
Related by keyword:
gg shell completion August 13, 2025 Linux, JavaScript, Bun, macOS
set -ex - The most useful bash trick of the year August 31, 2014 Linux
How to intercept and react to non-zero exits in bash February 23, 2023 Bash, GitHub
How post JSON with curl to an Express app April 15, 2020 Node, JavaScript