mremergo mremergo - 5 months ago 12
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.

#!/bin/bash

PS1='\u:\W\$ '


I tried
eval "PS1='\u:\W\$ '"
,
export PS1='\u:\W\$ '
and
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

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, yourscript.sh for a script which can be sourced by any POSIX shell), whereas scripts intended to be executed rather than sourced should have no extension.

Comments