erical
erical

Reputation: 365

how can I run different command according to the result of last command?

For example, there are 4 files (A,B,C,D) which I was try to upload with cURL, but sometimes it failed. My script is like this:

for f in `ls`
do
  curl -T $f ftp.server.com
done

A,B,C were uploaded successfully, while D left with some kind of errors. What I want to do is to remove A,B,C and keep only D in the directory.

Upvotes: 3

Views: 90

Answers (2)

sarnold
sarnold

Reputation: 104110

First things first, you've coded a bug into your little script:

for files in `ls`

This should read:

for files in *

The difference is that ls approach won't properly handle files with whitespace in their names:

$ ls -l
total 8
-rw-r--r-- 1 sarnold sarnold   15 2011-11-23 01:25 bad file
drwxr-xr-x 2 sarnold sarnold 4096 2011-11-21 03:07 blubber
$ for f in `ls` ; do echo === $f === ; done
=== bad ===
=== file ===
=== blubber ===
$ for f in * ; do echo === $f === ; done
=== bad file ===
=== blubber ===
$ 

Now, onto the upload-and-remove issue:

for f in * ; do curl -T $f ftp.example.com && rm $f ; done

The && is a short-circuit operator; it will execute the second command only if the first command returns an exit value of 0 (which normally means "successful" in process return values -- yes, a little backwards). You might also someday find the || operator useful, to execute programs if something has failed. And perhaps most surprising, you can use them both on one command to do something on success or failure as appropriate:

$ true && echo success || echo failure
success
$ false && echo success || echo failure
failure
$ 

Upvotes: 7

Brian Cain
Brian Cain

Reputation: 14619

$? refers to the return code. Assuming "0" indicates a successful curl upload, then you want something like this:

for files in `ls`
do
    curl -T $f ftp.server.com
    if [[ $? -eq 0 ]]; then
      rm $f
    fi
done

Upvotes: 3

Related Questions