-1

I have a script in bash :<

SERVER="screen_name"
INTERVAL=60
ISEXISTS=false

screen -ls | grep $'^\t' | while read name _rest ; do
   if[["$SERVER" = "$name"]];
        then echo "YEP" && ISEXISTS=true && break
   fi
done

if $ISEXISTS
then screen -dmS automessage
else exit 0

while true
do
screen -S $SERVER -X stuff "TEST\r"
sleep $INTERVAL
done

But when I try run it I have error:

line:13 syntax error near unexpected token `then'
Adrian Frühwirth
  • 42,970
  • 10
  • 60
  • 71
user1366028
  • 41
  • 2
  • 9

2 Answers2

0

OK now i have

ISEXISTS = false
screen -ls | grep $'^\t' | while read name _rest ; do
  if [[ "$name" == *"$SERVER"* ]];
    then ISEXISTS=true
  fi
done

and when i set ISEXISTS to true this not work :F i test it and in loop ISEXISTS = true but outside loop ISEXISTS = false :<

user1366028
  • 41
  • 2
  • 9
  • Yes, because you forced `while` to run in a sub shell (hence the limited scope). In order to pipe to `while`, bash needs to wrap it in a subshell, otherwise bash is piping to self, this is done automagically, hence the surprise: "where did that subshell come from?". No worries everyone has been bitten by that one. ;-) – thom Nov 25 '13 at 01:14
  • Besides that: `ISEXISTS = false` should be `ISEXISTS=false`. No spaces are allowed in assignments – thom Nov 25 '13 at 01:16
0

try this:

ISEXISTS=false
while read name _rest
do
    if [[ "$name" == *"$SERVER"* ]];
        then ISEXISTS=true
    fi
done < <( screen -ls | grep $'^\t' )

It will keep your variables accessible. In the last line we let the screen and grep run in a subshell and feed their output through an anonymous filedescriptor to the while statment (which doesn't need a subshell this way)

The other way is:

ISEXIST=$( 
           screen -ls | grep $'^\t' | while read name _rest
           do
               if [[ "$name" == *"$SERVER"* ]];
               then echo "true"
               fi
           done
         )

Like, who cares if it is running in a subshell, as long as we can get our variables. In this case by echoing the variable and catching the output from the subshell echo by using $()

An empty string is evaluated as false so we don't need to explicitly assign that in this example.

thom
  • 2,294
  • 12
  • 9