24

I'd like to find an equivalent of

cmd 1 && cmd 2 && ... && cmd 20

but with commands expressed within a for loop like

for i in {1..20}
do
   cmd $i
done

What would you suggest to change in the second expression to find an equivalent of the first?

54

The equivalent to your original sequence would be:

for i in {1..20}
do
   cmd $i || break
done

The difference with Amit's answer is the script won't exit, i.e. will execute potential commands that might follow the sequence/loop. Note that the return status of the whole loop will always be true with my suggestion, this might be fixed if relevant in your case.

  • 1
    Agreed, this more closely follows the behaviour of cmd && cmd – Amit Gold Oct 23 '16 at 10:46
9

If you want a dirty one-line solution, you can create a command and send it to bash.

echo "cmd "{1..20}" &&" : | bash
  • 3
    we should create an IObashCC ^^ – Olivier Dulac Oct 24 '16 at 17:34
8

You can break out of the loop if one of them failed

for i in {1..55}; do
    if ! cmd $i; then
        exit 1
    fi
done
  • 1
    like @jiliagre noted (and provided a correction in his answer), this does not "break out of the loop", it exits the calling shell. – Olivier Dulac Oct 24 '16 at 17:32
  • 1
    Isn't break legal there? I'm pretty sure the if statement doesn't interfere.. – jpaugh Oct 24 '16 at 17:58
0

This is how i execute my tasks in terminal without using &&

 for i in google.com yahoo.com;do ping -c1 $i;echo $i;done

Similar to you have to put this command in a script

 for i in google.com yahoo.com
    do echo $i;ping -c1 $i;
  done

Both giving same output to me

google.com PING google.com (172.217.26.174) 56(84) bytes of data. 64 bytes from google.com (172.217.26.174): icmp_seq=1 ttl=56 time=259 ms

--- google.com ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 259.794/259.794/259.794/0.000 ms yahoo.com PING yahoo.com (98.138.253.109) 56(84) bytes of data. 64 bytes from yahoo.com (98.138.253.109): icmp_seq=1 ttl=51 time=398 ms

--- yahoo.com ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 398.974/398.974/398.974/0.000 ms

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.