TSGM
TSGM

Reputation: 263

Why does this if statement give me an error

Can someone explain why this simple bash script:

#!/bin/bash

myvar="Hello"

if [[ -z "$myvar" ]]; then
    # echo "It's an unfilled string"
else
    echo "It's a filled string!"
fi

gives me the error

./testscript: line 7: syntax error near unexpected token `else'
./testscript: line 7: `else'

However, if I remove the comment on the echo line, the script runs fine. Obviously, there is an issue with having commented lines within empty if statements. This this in mind, how do I fix it so I can have an empty if statement with comments?

Upvotes: 2

Views: 89

Answers (2)

AkihikoTakahashi
AkihikoTakahashi

Reputation: 159

This is the way not to use if else statement.

#!/bin/bash

myvar="Hello"

[[ -n "$myvar" ]] && echo "It's a filled string!"

Also you can use this.

#!/bin/bash

myvar="Hello"

[[ -z "$myvar" ]] || echo "It's a filled string!"

Upvotes: 1

Tom Fenech
Tom Fenech

Reputation: 74596

There are no statements between then and else, so this is a syntax error. If you really want to do nothing in the if branch, then you can use a : (or true) as a placeholder:

#!/bin/bash

myvar="Hello"

if [[ -z "$myvar" ]]; then
    # echo "It's an unfilled string"
    :
else
    echo "It's a filled string!"
fi

Better yet, reverse your logic:

#!/bin/bash

myvar="Hello"

if [[ -n "$myvar" ]]; then
    echo "It's a filled string!"
fi

Upvotes: 6

Related Questions