Search code examples
bashsolaris

Will bash script pre-parse the syntax?


I am running bash script that needs to run different code for SunOs and Linux and I am getting the syntax error from the part of the code that not supposed to be true. I did not expect that since I thought that Bash works as interpreter.

The bash version on SunOS is 2.5 and on Linux is 4.1. The syntax it complains about is only supported from 3.1 version.

I tried to disable the newer code with "else" clause but it looks like it still pre-parses.

Also my script has ":" instead of "#! /bin/sh" as first line.

test.sh:

:
echo "`uname`"
if [ `uname` = "SunOS" ]
 then
    echo "do old stuff"
 else
    echo "new stuff"
    arr=($(grep "^X1" ../foo.txt | sed 's/.*=//'))
fi

The error is

> ./test.sh
SunOS
./test.sh: syntax error at line 8: `arr=' unexpected

If I comment error line then it will work fine:

:
echo "`uname`"
if [ `uname` = "SunOS" ]
 then
    echo "do old stuff"
 else
    echo "new stuff"
    #arr=($(grep "^X1" ../foo.txt | sed 's/.*=//'))
fi

The result is

> ./test.sh
SunOS
do old stuff

My question is how do I fix this syntax error without commenting? I have to have "if/else" to be able to run this script on different machines.


Solution

  • That array syntax has been supported in bash since at least version 2; if you're getting errors there, it's because your script is not running under bash at all, but under some other shell. This probably has a lot to do with your script starting with : instead of a shebang line, meaning it's up to whatever runs the script to figure out what to run it with, with inconsistent results. I'd strongly recommend using a proper shebang line. If bash doesn't exist in a predictable location, you could use #!/usr/bin/env bash. If bash might not be in the PATH, you could use something like the script prologue here -- a #!/bin/sh shebang followed by commands to find and switch to bash.

    As for the question about pre-parsing: yes, bash and other shells will parse all the way to the fi keyword before executing the if construct. They need to find the then, else, and fi keywords in order to figure out what they're going to execute and what they're going to skip, and in order to find those they have to parse their way to them.