mremergo mremergo - 1 year ago 75
Bash Question

Changing bash prompt temporarily by own script

I wanted to write a tiny shell script that shortens the commmand prompt when it gets too long. Setting the PS1 variable in bash works fine. When I try the same command directly in a script and run it, nothing happens.


PS1='\u:\W\$ '

I tried
eval "PS1='\u:\W\$ '"
export PS1='\u:\W\$ '
exec PS1='\u:\W\$ '
without any result.

How can I achieve the same result as a direct input in the bash?

Thank you in advance

Answer Source

In general, in UNIX, a process can only change variables for itself and its children -- not its parent ("its parent" being the process that invoked it).

You need to source a script, not execute it, for it to be able to effect your parent shell's variables. This executes all commands inside the script inside your current script, not a new child process (whose variables' values are thrown away on exit).

# in bash
source yourscript

# or in POSIX sh
. yourscript # mind the space!

In this usage, the shebang does nothing; similarly, the +x permission isn't needed either. It's also typical to name scripts intended to be sourced rather than executed with an extension mapping to the shell they're intended to be used by (yourscript.bash for bash, for a script which can be sourced by any POSIX shell), whereas scripts intended to be executed rather than sourced should have no extension.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download