Thursday, January 23, 2014

Bash loops

As simple as it comes, loop round 10 times

#!/bin/bash

for i in {1..10}
do
  echo ${i}
done


Similar, but stepping in up in 2s

#!/bin/bash

for i in {1..10..2}
do
  echo ${i}
done


Loop from 1 to 10, but continue if i = 4 (so the continue statement makes execution return to the top of the for loop)

#!/bin/bash

for i in {1..10}
do
  if [ ${i} -eq 4 ]; then
    continue
  fi
  echo ${i}
done





And iterate over files in a directory


#!/bin/bash
 
for file in /tmp/*
do
  ls -l ${file}
done

No comments:

Post a Comment