'echoing PROMPT_COMMAND from terminal and from bash script

while trying to write a bash script i encountered a strange issue when i try to execute it. i want to echo the $PROMPT_COMMAND variable thus, i have the following piece of bash script

#!/bin/bash 
echo $PROMPT_COMMAND

executing this script echoes nothing. why is that? it does not make sense as when i do execute

echo $PROMPT_COMMAND

from the command prompt, i get the content that is stored inside the PROMPT_COMMAND

so... what am i doing wrong, what is missing?

a thing about the environment: tried this on ubuntu 20



Solution 1:[1]

The problem is based on how you are executing your script and what environment it is using.

After making the file executable, there are two ways of running it:

  1. ./script.sh
  2. . script.sh

The first way executes it in a new bash subshell, which doesn't have access to the $PROMPT_COMMAND variable since it is by definition, new.

The second way executes the script within the context of your current shell. This means it has access to the $PROMPT_COMMAND variable. This is the right way to proceed. Anytime you need to work on your prompt, you need to execute it this way.

Note: #2 is the same as running source script.sh. It is also referred to as "sourcing" your script. Just in case you run into these terms, you'll know what they mean.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dean Householder