Basic SH Scripting Help

Status
Not open for further replies.

flere-imsaho

Ars Legatus Legionis
10,674
Subscriptor
Hi all,

I'm trying to test for a non-zero exit response from a command in a shell script, but pretty transparently.

Here's the English syntax of what I want to do:

1. Copy stuff to stuff2
2. If the copy doesn't work, report an error and end the script
3. If it works fine, then keep on going.

Now this works OK:

code:<HR>
Code:
#!/bin/sh<P>if cp stuff stuff2
then
     echo
else
     echo copy failed
     exit 1
fi<P>echo moving on with the script<P>

The problem is that I can't get rid of having to do something if it's OK. Simply putting then and then right on to else gives a script error.

Better would be to test for the non-success of the copy, i.e.:

code:<HR>
Code:
#!/bin/sh<P>if !(cp stuff stuff2)
then
     echo didn't work
     exit 1
fi

But this doesn't work.

Anyway, any ideas?
 

Spizay

Ars Scholae Palatinae
1,175
Subscriptor++
But this doesn't work.

Why not? Did you put it in exactly as it's shown? That single quote might have thrown you off, but this:

code:<HR>
Code:
#!/bin/sh
if ! ( cp stuff stuff2 )
then
  echo "Did not work."
  exit 1
fi

Should work. If not, what error do you get?

Course I'm in windows right now so I have to assume that cp will return a non-zero RC upon failure, right? I don't remember off the top of my head.

Try the 'true' command. It's a successful no-op.

Or you can use the colon ':', it works too :)
 
Status
Not open for further replies.