Re: shell script question - changing PS1 based on tty
On 2007-05-30, mowgli wrote:
> I just made a simple shell script for changing the color username in
> the PS1 prompt. The same commands if given one by one on the command
> line, change the prompt as per the commands, all fine. But if the
> script is executed, the prompt does not change. However the echo
> statement is echoed fine and echo $? returns true.
>
> Can someone check what is the problem with the script that these
> commands execute fine on the CLI and not from inside the script?
You must source the script, or it will have no effect in the
current shell.
> Here's the script:
>
> #!/bin/bash
> # Purpose: To change prompt color based on tty number
tty=`tty` ## See below
> # root's PS1, regardless of tty
> ROOTPS='\[[01;31m\]root\[[00m\]:\[[01;36m\]\w\[^[[00m\]$ '
> # Colored PS1 based on tty number
> TTY1PS='\[[01;32m\]`whoami`\[^[[00m\]:\[[01;36m\]\w\[[00m\]$ '
> TTY2PS='\[[01;33m\]`whoami`\[^[[00m\]:\[[01;36m\]\w\[[00m\]$ '
> TTY3PS='\[[01;34m\]`whoami`\[^[[00m\]:\[[01;36m\]\w\[[00m\]$ '
> TTY4PS='\[[01;35m\]`whoami`\[^[[00m\]:\[[01;36m\]\w\[[00m\]$ '
> TTY5PS='\[[01;36m\]`whoami`\[^[[00m\]:\[[01;36m\]\w\[[00m\]$ '
> TTY6PS='\[[01;37m\]`whoami`\[^[[00m\]:\[[01;36m\]\w\[[00m\]$ '
>
> if [ `echo $UID` = 0 ]
if [ "$UID" -eq 0 ]
> then
> PS1=$ROOTPS # Set root's PS1
>
> elif
> [ `tty` = '/dev/tty1' ]
Don't call tty every time; store the result in variable and compare that.
elif [ "$tty" = /dev/tty1 ]
> then
> PS1=$TTY1PS
> echo "You are on `tty`"
>
> elif
> [ `tty` = '/dev/tty2' ]
> then
> PS1=$TTY2PS
> echo "You are on `tty`"
>
> elif
> [ `tty` = '/dev/tty3' ]
> then
> PS1=$TTY3PS
> echo "You are on `tty`"
>
> elif
> [ `tty` = '/dev/tty4' ]
> then
> PS1=$TTY4PS
> echo "You are on `tty`"
>
> elif
> [ `tty` = '/dev/tty5' ]
> then
> PS1=$TTY5PS
> echo "You are on `tty`"
>
> elif
> [ `tty` = '/dev/tty6' ]
> then
> PS1=$TTY6PS
> echo "You are on `tty`"
>
> else
> # This won't ever get echoed, or shouldn't.
> echo "You are not a valid user of this system."
> exit 1
> fi
I'd shorten the script to:
if [ "$UID" -eq 0 ]
then
PS1='\[[01;31m\]root\[[00m\]:\[[01;36m\]\w\[^[[00m\]$ '
else
tty=`tty`
case $tty in
/dev/tty[1-6])
echo "You are on $tty"
num=$(( ${tty#/dev/tty} + 1 ))
PS1='\[[01;3${num}m\]`whoami`\[^[[00m\]:\[[01;36m\]\w\[[00m\]$ '
;;
*) echo "You are not a valid user of this system."
exit 1
;;
esac
fi
If the name of the script is setPS1, call it this way:
.. setPS1
Or (bash only):
source setPS1
--
Chris F.A. Johnson, author <http://cfaj.freeshell.org/shell/>
Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)
===== My code in this post, if any, assumes the POSIX locale
===== and is released under the GNU General Public Licence
|