nevernew
nevernew

Reputation: 672

Bash IF statement: string comparison of command output always false

Hi I'm trying to write a simple bash script to attach to a screen session. If the session is not already started then it will start it and try to attach again.

The problem I'm having is with the if statement; it should compare the output from the screen command with the failure message and if they are equal go on to start the session and attach. But it's always going to the else clause, printing out the error message I was checking against :s

Both strings contain the same thing:

"There is no screen to be attached matching sctest."

but bash thinks they are different...

Here's the bash script, what am I missing?

#!/bin/bash

screenOutput=$(screen -aA -x sctest);
failString="There is no screen to be attached matching sctest.";

if [ "$screenOutput" = "$failString" ]; then
    echo "screen session not started. starting now...";

    # . ./init.sh

    # echo $(screen -aA -x sctest);
else
    echo "$screenOutput";
fi

Upvotes: 4

Views: 1986

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295639

Use set -x (or invoke bash -x yourscript) to print each line as it's evaluated with values expanded in a way that makes hidden characters visible and human-readable.

Most likely, you'll see something like the following:

[ 'There is no screen to be attached matching sctest' = $'There is no screen to be attached matching sctest\r' ]

...with the latter having a \r on the end. This is a carriage-return.

To remove it, you can modify your code like so:

screenOutput=$(screen -aA -x sctest)
screenOutput=${screenOutput%$'\r'}

Upvotes: 3

Related Questions