Afficher un message
Vieux 30/05/2007, 06h13   #3
Chris F.A. Johnson
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut 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='\[\]root\[\]:\[\]\w\[^[[00m\]$ '
> # Colored PS1 based on tty number
> TTY1PS='\[\]`whoami`\[^[[00m\]:\[\]\w\[\]$ '
> TTY2PS='\[\]`whoami`\[^[[00m\]:\[\]\w\[\]$ '
> TTY3PS='\[\]`whoami`\[^[[00m\]:\[\]\w\[\]$ '
> TTY4PS='\[\]`whoami`\[^[[00m\]:\[\]\w\[\]$ '
> TTY5PS='\[\]`whoami`\[^[[00m\]:\[\]\w\[\]$ '
> TTY6PS='\[\]`whoami`\[^[[00m\]:\[\]\w\[\]$ '
>
> 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='\[\]root\[\]:\[\]\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\]:\[\]\w\[\]$ '
;;
*) 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
  Réponse avec citation
 
Page generated in 0,07025 seconds with 9 queries