Here's a little bash script I wrote which runs ngrok
in the background. It then tries to sets a NGROK_PUBLIC_URL
variable by calling a curl
command (against http://127.0.0.1:4040/api/tunnels) followed by a sed
command (which extracts the ngrok public URL). This all runs inside a loop until NGROK_PUBLIC_URL
has a valid value as it normally takes ngrok 2 or 3 seconds for it's tunnels to become established.
start-ngrok.sh
#!/bin/sh
# Set local port from command line arg or default to 8080
LOCAL_PORT=${1-8080}
echo "Start ngrok in background on port [ $LOCAL_PORT ]"
nohup ngrok http ${LOCAL_PORT} &>/dev/null &
echo -n "Extracting ngrok public url ."
NGROK_PUBLIC_URL=""
while [ -z "$NGROK_PUBLIC_URL" ]; do
# Run 'curl' against ngrok API and extract public (using 'sed' command)
export NGROK_PUBLIC_URL=$(curl --silent --max-time 10 --connect-timeout 5 \
--show-error http://127.0.0.1:4040/api/tunnels | \
sed -nE 's/.*public_url":"https:..([^"]*).*/\1/p')
sleep 1
echo -n "."
done
echo
echo "NGROK_PUBLIC_URL => [ $NGROK_PUBLIC_URL ]"
The script takes a port as an optional command line argument i.e.
$ . start-ngrok.sh 1234
Run NGROK in background on port [ 1234 ]
Extracting ngrok public url ...
NGROK_PUBLIC_URL => [ 75d5faad.ngrok.io ]
... but will run on port 8080
if the port isn't supplied ...
$ . start-ngrok.sh
Run NGROK in background on port [ 8080 ]
Extracting ngrok public url ...
NGROK_PUBLIC_URL => [ 07e7a373.ngrok.io ]
The NGROK_PUBLIC_URL
now contains the public url i.e.
$ echo $NGROK_PUBLIC_URL
07e7a373.ngrok.io
This can be accessed / used in your applications.
Note: This script needs to be sourced (. start-ngrok.sh
OR source start-ngrok.sh
). This is because it is setting an environment variable which wont be available if run normally in a new shell (i.e. ./start-ngrok.sh
). See https://superuser.com/q/176783 for more info.
You can also create a little script using pkill
/ kill
etc to stop the background ngrok
process: -
stop-ngrok.sh
#!/bin/sh
echo "Stopping background ngrok process"
kill -9 $(ps -ef | grep 'ngrok' | grep -v 'grep' | awk '{print $2}')
echo "ngrok stopped"