1

I have the following simple shell script:

#   get all servers from config
sshservers=`node $scriptDir/readconfig.js --command cluster.sshservers`

#for each server
for server in sshservers
do

    #run deployserver with server (server:port format) argument
    if ! sh deployserver --server $server
    then
        exit 1 #failure
    fi

done

Now, the node command to get the sshservers may return an exit code that is nonzero. When this happens, things went horribly wrong and so I would like to quit with an error message.

How would I do this? Would this be the most appropriate way?

sshservers=`node $scriptDir/readconfig.js --command cluster.sshservers`
if ! $?
then
    echo "Error: node readconfig tool failed."
    exit 1
fi

Also, how do I output the stderr of this node command when things go so horribly wrong?

Finally, is the way I exit when sh deployserver fails proper, or should this be done differently?

4 Answers 4

2

To see if the last command was sucessfull you can do this :

if [ "$?" != "0" ]
    then
        //do something
    fi

The stderr should find it's way to the console you are running the script by itself.

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

Comments

2

It looks a bit strange, but it is legal to do:

sshservers=$( node ... ) || exit 1

Note that you do not need to emit an error message, since the node command ought to have printed a useful error diagnostic before it exited. You can also simply add set -e at the start of the script, which will cause your script to abort if any assignments of this form terminate. The return value of the assignment is the return value of the "inner" command, so the normal techniques all apply.

1 Comment

Yep, this is clean and a practice that can be seen reflected in Perl.
1

Use $?, which contains the exit code from the last run command. So you can do:

sshservers=`node $scriptDir/readconfig.js --command cluster.sshservers`
[[ "$?" == "0" ]] || exit 1

The way you exit from sh deployserver is the way I would do it. You could use $? if you want, but the way you have it is shorter and cleaner IMHO.

Comments

1

You can also put the assignment into an if statement:

if ! sshservers=$(node $scriptDir/readconfig.js --command cluster.sshservers)
then
  echo "oops, node command returned non-zero"
  exit 1
fi

for server in $sshservers; do ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.