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.
eval "PS1='\u:\W\$ '"
export PS1='\u:\W\$ '
exec PS1='\u:\W\$ '
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.