7

Can anyone tell me why this bash script works if I cut and paste it to the terminal but throws "server_prep.sh: 7: Syntax error: "(" unexpected" when launched using $ sudo sh server_prep.sh ?

#!/bin/sh

#Packages
apt-get -y install ssh libsqlite3-dev ruby-full mercurial

#Gems
required_gems = ( rake rails sqlite3-ruby )

#Set up directories
[ ! -d /var/www ] && mkdir /var/www
[ ! -d /var/www/apps ] && mkdir /var/www/apps

#install gems manually
if ! which gem >/dev/null; then
    wget http://rubyforge.org/frs/download.php/60718/rubygems-1.3.5.tgz
    tar xvfz rubygems-1.3.5.tgz
    ruby rubygems-1.3.5/setup.rb
    ln -s /usr/bin/gem1.8 /usr/bin/gem
    gem update --system

    #Tidy Up
    rm -rf rubygems-1.3.5.tgz rubygems-1.3.5
fi

#Install required gems
for required_gem in "${required_gems[@]}"
do
    if ! gem list | grep $required_gem >/dev/null; then
        gem install $required_gems
    fi
done

Thanks in advance!

1
  • 1
    Do you also get the error for "sudo /bin/bash server_prep.sh" ? Commented Sep 13, 2009 at 19:36

2 Answers 2

19

Are you on ubuntu?

Then you should change the #!-line at the top to read #!/bin/bash because /bin/sh is a very limited shell.

This would explain why works in the terminal (where the shell is bash) but not as a shell script (which is run by /bin/sh).

They changed this a couple of releases ago for performance reasons - most people don't need full bash functionality for shell script, and this limited shell is much faster at startup.

Edit: I just noticed that you don't even have to use an array since you convert it to a space separated string in the for loop anyway. Just remove the parenthesis in the assignment and put quotes around it instead (and also remove the spaces around the equal sign, as hacker suggested)

Sign up to request clarification or add additional context in comments.

5 Comments

Changing dash to bash is a good idea, but this script is not supposed to work on terminal either…
good point. And I just noticed, there's really no nead to use an array in the first place, since it's converted to a space separated string anyway :)
Shame I can't split the accept as you both were right. Thanks!
heh, Isak, that's true, but if array elements contained spaces the array would come in handy ;-)
I got bit by this… so used to running 'bash' scripts with sh foo.sh
7

Try

required_gems=( rake rails sqlite3-ruby )

instead (note the lack of spaces around '=').

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.