LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash: How to tell a tty from a pts? (https://www.linuxquestions.org/questions/programming-9/bash-how-to-tell-a-tty-from-a-pts-83382/)

m0rl0ck 08-19-2003 01:54 AM

Bash: How to tell a tty from a pts?
 
This is what I have:

#!/bin/bash
echo $(tty)
if "$(tty)" == "*pts*" ;
then

echo yes
fi


What Im getting is:
/dev/pts/1
./test: line 3: /dev/pts/1: Permission denied

What I want is:
/dev/pts/1
yes

Appatently the script is interpreting the line if "$(tty)" == "*pts*" ; as an attempt to access the device rather than as a string comparision.

Anyone know a way to get this script to echo "yes" or how to tell a pts from a tty using bash?

shishir 08-19-2003 05:47 AM

firstly you are using the if condition in a wrong way...at the time of comparison in the if statement ...it tries to execute the command in the tty variable...
so the right way of using an if statement
if [ $tty = "*pts* ]

second this would not help you compare the two strings as in this case the *pts* doesnt translate to meta-characters..ie...your comparison would always fail..youd have to do some sort of string parsing....awk is the easiest way out....
echo $tty | awk '{s=match($0,"pts");if (s == 0) print ""not found " else print "found",print $0 }'
this will give you the output you want

Hko 08-19-2003 06:25 AM

Quote:

so the right way of using an if statement
if [ $tty = "*pts* ]
No. tty is a command, not a variable. So the output of the tty command needs to be captured using backticks: `tty` or using $(tty).

One way to do it:
Code:

#!/bin/bash

if tty | fgrep pts ; then
        echo yes
fi

Or, another:
Code:

#!/bin/bash

TTY=$(tty)
TMP=${TTY%/*}
TMP=${TMP##*/}

echo $TTY
if [ "$TMP" == "pts" ] ; then
        echo yes
fi


shishir 08-19-2003 07:16 AM

yeah i know that tty is a command, but i sure can take the output of tty in a variable, named tty..by doing tty=`tty`.....that is what i am saying....

but i think you are right ..m0rl0ck is confused how to use the commands and variables in the if statement..

i did not know about the string manipulation like you showed in your later example....

i used awk as i was just dabbling with it for similar purposes right now...:)

m0rl0ck 08-21-2003 07:26 AM

Thanks for the help :)
String comparisions in shell dont seem as straight forward as in php or perl.
Decided to go with your example using fgrep, its short and to the point, thanks again.


All times are GMT -5. The time now is 10:12 AM.