Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert an environment variable inside the bash prompt

I can set an environment variable inside the bash prompt like this:

export PS1="[\u@\H/$FOO \W]\$ " 

The prompt does not change when I change the environment variable: $FOO because the $FOO variable is not interpreted.

I can work around it by doing the following, exporting PS1 again. But I would like to be able to do it on one line:

[user@server ]$ echo $FOO foo [user@server ]$ export PS1="[$FOO]$ " [foo]$ export FOO=bla [bla]$  

Can this be done in one line?

like image 942
Bernd Avatar asked Sep 09 '11 09:09

Bernd


People also ask

How do I set an environment variable in bash?

The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.

How do I set an environment variable in shell?

To set an environment variable everytime, use the export command in the . bashrc file (or the appropriate initialization file for your shell). To set an environment variable from a script, use the export command in the script, and then source the script. If you execute the script it will not work.

How do I declare a variable in bash?

A variable in bash is created by assigning a value to its reference. Although the built-in declare statement does not need to be used to explicitly declare a variable in bash, the command is often employed for more advanced variable management tasks.


2 Answers

you need to add backslash to get it evaluated not in the time of FOO assigment but during evaluating the PS1, so do:

export PS1="[\$FOO]$ " 

instead of:

export PS1="[$FOO]$ " 

Note the \ before the $FOO.

like image 161
Michał Šrajer Avatar answered Oct 18 '22 23:10

Michał Šrajer


Try setting the PROMPT_COMMAND variable:

prompt() {     PS1="[$FOO]$ " }  PROMPT_COMMAND=prompt 

From http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x264.html:

Bash provides an environment variable called PROMPT_COMMAND. The contents of this variable are executed as a regular Bash command just before Bash displays a prompt.

like image 21
Arnaud Le Blanc Avatar answered Oct 18 '22 22:10

Arnaud Le Blanc