1

I'm having some trouble with the != section of the if statement. Essentially this statement is valid as far as I'm aware, however executing this gives [: 1: !=: unexpected operator. I've tried executing using -n but for whatever reason, even if the output is blank, using -n still runs the echo command.

Any help on this is appreciated. I've attached the code snippet below.

#!/bin/sh

HOST=$1
USER="/scripts/whoowns $HOST | tr -d '\r'"

ssh -t $HOST -p 22 -l deehem "sh -c 'if [ "" != "\`$USER\`" ]; then echo "Username for $HOST: \`$USER\`"; fi' ; bash -login"
Share a link to this question
CC BY-SA 3.0
1
0

As you realised, "bla "" bla" is just two strings concatenated ("bla bla").

You can escape the ": \", but the standard [ test tool has an option specifically for this task:

   -n STRING
          the length of STRING is nonzero

   -z STRING
          the length of STRING is zero

Note: why do you have \`? That way the string is never going to be empty....

Share a link to this answer
CC BY-SA 3.0
0

In regards to your "however executing this gives [: 1: !=: unexpected operator" problem, here is a solution:

Use bash -c instead of sh -c. The bash program seems to be better than sh at handling square brackets. For example:

ubuntu@ubuntu:/$ echo "antipetalous" | if [[ "antipetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi
match
ubuntu@ubuntu:/$ echo "antepetalous" | if [[ "antepetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi
no
ubuntu@ubuntu:/$ sh -c 'echo "antipetalous" | if [[ "antipetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi'
sh: 1: [[: not found
no
ubuntu@ubuntu:/$ bash -c 'echo "antipetalous" | if [[ "antipetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi'
match
ubuntu@ubuntu:/$ bash -c 'echo "antepetalous" | if [[ "antepetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi'
no
ubuntu@ubuntu:/$ sh -c 'echo "antepetalous" | if [[ "antepetalous" =~ "ti" ]]; then echo "match"; else echo "no"; fi'
sh: 1: [[: not found
no
ubuntu@ubuntu:/$

So ssh -t $HOST -p 22 -l deehem "sh -c 'if [ "" != ... would become ssh -t $HOST -p 22 -l deehem "bash -c 'if [ "" != ....

Thanks to pLumo at https://askubuntu.com/questions/1310106/sh-c-sh-not-working-when-using-if-statement-and-having-in-the-filena ("command line - sh -c '...' sh {} not working when using if statement and having ' in the filename - Ask Ubuntu").

Share a link to this answer
CC BY-SA 4.0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.