joaop
joaop

Reputation: 95

Unexpected `then' bash script

How do I fix this error? I can't see anything wrong with my syntax.

ipcheck() {
  echolog "[INFO] Enabling IP Forwarding..."
  sudo echo 1 > /proc/sys/net/ipv4/ip_forward
  if[$(cat /proc/sys/net/ipv4/ip_forward) == "0"]
    then
    echolog "[CRITICAL] Could not enable IP Forwarding!"
    exit 0
  fi
  echolog "[INFO] IP Forwarding successfully enabled!"
}

I know this is a very basic script, but it's part of a bigger one. The error happens on the then statement.

Upvotes: 2

Views: 4881

Answers (4)

Jite
Jite

Reputation: 4368

Slightly refactored (improved) version that is not bash dependant:

#!/bin/sh

ipcheck() {
    echolog "[INFO] Enabling IP Forwarding..."
    sudo echo 1 > /proc/sys/net/ipv4/ip_forward || {
        echolog "[CRITICAL] Error echoing to ip_forward file"
        exit 1
    }

    # Paranoia check :)
    status=$(cat /proc/sys/net/ipv4/ip_forward)
    [ "$status" = "1" ] || {
        echolog "[CRITICAL] Could not enable IP Forwarding!"
        exit 1  # 1 is error in scripts, 0 is success
    }
    echolog "[INFO] IP Forwarding successfully enabled!"
}

Preferably make an error() function, perhaps something like:

# Call it like: error "[INFO] Could not ..."
error() {
    echolog "$*"
    exit 1
}

Oh and yeah, as everyone else pointed out, don't forget the spaces :)

Upvotes: 0

user559633
user559633

Reputation:

Place a space between the if and [$(cat...] section on line 4. For this script to run, you'll also need a space on the ] on the same line.

On a related note, if you're not using indentation in your shell scripts, you should seriously consider it as it makes maintenance and legibility of your code much easier.

Upvotes: 3

Steve
Steve

Reputation: 1243

The problem is that you need a space between if and [. The lack of a space is confusing bash's parser.

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 224944

Shell scripting tends to be a lot more whitespace sensitive than you might be used to if you've come from other programming languages (read: C). Your if line has the problems. You are probably looking for:

if [ $(cat /proc/sys/net/ipv4/ip_forward) == "0" ]

The thing to remember here is that [ is not part of any special if syntax - it's the name of a program (sometimes a shell builtin). If you think of it like that, you can see how the command line parser needs it to be separated. Similarly, the [ command (or builtin) expects the closing ] to be separated from its other arguments, so you need a space before it, too.

Upvotes: 6

Related Questions