Posts Tagged ‘loop’

Reading a file line by line in Bash

Posted: 26th July 2015 by Tim in Bash, Linux
Tags: , , , , , , ,

There are a few ways to read a file in bash, each with their own caveats. If you’re looking to read a file line-by-line verbatim, including blank lines, then using a simple while loop should do the trick. For example, the following code will print the contents of a file with line numbers: line_no=0 while […]

Linux Terminal Clock

Posted: 9th March 2015 by Tim in Bash, Linux
Tags: , , , , , , , , ,

Ever wanted to have a real-time clock on your linux terminal? We can create one with a single line of bash, like so: while echo -en “$(date)\r”; do sleep 1; done Let’s look at how this works: date is a common unix tool used to print the current date and time. The $(…) means that […]

Do until script succeeds in bash

Posted: 12th September 2013 by Tim in Bash, Linux
Tags: , , , , , ,

Occasionally you want to continue retrying a script or program until it succeeds. In bash, this can be done using the until … do … done syntax, like so: until (<command>); do echo “FAIL!”; sleep 10; done For example, if you wanted to halt processing until a program.log file was created, you could do something […]

C and C++ code is generally pretty easy to make sense of. But there are a few oddities which can catch you out and can send you into an endless debugging exercise if you’re not careful. One such oddity is conditional evaluation. Consider the following code which keeps track of three numbers. Look through the […]