So many of you, this is so basic that it's embarrassing. Any maybe to me too. But the truth is, I often forget the syntax. By mentioning it here, hopefully, I'll memorize it better.

To set a default environment variables, consider this example Bash program:


#!/bin/bash

: "${PORT:=8000}"

echo "Port number: $PORT"

When you run it, it defaults to the value 8000 (a string)


❯ bash dummy.sh
HOSTNAME:8000

And if you override the default:


❯ PORT=1234 bash dummy.sh
Port number: 1234

Note, you don't have to "define" the default on its own line. You can simplify it by defining the default where you use the environment variables. E.g:


#!/bin/bash

echo "Port number: ${PORT:=8000}"

This works the same.

Comments

Your email will never ever be published.

Previous:
Comparing Deno vs Node vs Bun August 5, 2024 JavaScript, Bun
Next:
Wouter + Vite is the new create-react-app, and I love it August 16, 2024 Node, React, Bun
Related by category:
How to intercept and react to non-zero exits in bash February 23, 2023 Bash
Find the largest node_modules directories with bash September 30, 2022 Bash
How to count the most common lines in a file October 7, 2022 Bash
./bin/huey-isnt-running.sh - A bash script to prevent lurking ghosts June 10, 2020 Bash