Integrate docker context show into your shell prompt
In this step, we will integrate the docker context show
command into your shell prompt. This allows you to see the current Docker context directly in your terminal prompt, making it easier to keep track of which Docker daemon you are interacting with.
We will modify the .zshrc
file in your home directory, which is the configuration file for the Zsh shell. We will add a function that gets the current Docker context and then include this function's output in the prompt string.
First, open the .zshrc
file using the nano
editor:
nano ~/.zshrc
Scroll to the end of the file and add the following lines:
## Function to get current Docker context
get_docker_context() {
docker context show 2> /dev/null
}
## Add Docker context to prompt
PROMPT='$(get_docker_context) %~ %## '
Let's break down these lines:
get_docker_context()
: This defines a new shell function named get_docker_context
.
docker context show 2>/dev/null
: Inside the function, this command gets the current Docker context. 2>/dev/null
redirects any error output to /dev/null
, preventing it from cluttering the prompt if Docker is not running or there's an issue.
PROMPT='$(get_docker_context) %~ %## '
: This line sets the PROMPT
environment variable, which defines the appearance of your shell prompt.
$(get_docker_context)
: This executes the get_docker_context
function and includes its output in the prompt.
%~
: This displays the current working directory, with the home directory abbreviated as ~
.
%#
: This displays a #
if you are the root user or a %
if you are a regular user.
Save the file by pressing Ctrl + X
, then Y
, and then Enter
.
To apply the changes to your current terminal session, you need to source the .zshrc
file:
source ~/.zshrc
After sourcing the file, your shell prompt should now display the current Docker context (which should be default
) before the current directory.
You can test this by switching to the my-context
again:
docker context use my-context
Your prompt should update to show my-context
followed by your current directory.
Then switch back to the default context:
docker context use default
Your prompt should change back to showing default
.