Scripting

Bash functions

As in almost any programming language, you can use functions to group pieces of code in a more logical way or practice the divine art of recursion. Declaring a function is just a matter of writing function my_func { my_code }. Calling a function is just like calling another program, you just write its name. […]

Read More
Linux

Bash loops for, while and until

The for loop is a little bit different from other programming languages. Basically, it let’s you iterate over a series of ‘words’ within a string. The while executes a piece of code if the control expression is true, and only stops when it is false (or a explicit break is found within the executed code. […]

Read More
Scripting

Bash redirection

Theory and quick reference There are 3 file descriptors, stdin, stdout and stderr (std=standard). Basically you can: redirect stdout to a file redirect stderr to a file redirect stdout to a stderr redirect stderr to a stdout redirect stderr and stdout to a file redirect stderr and stdout to stdout redirect stderr and stdout to […]

Read More
Scripting

Using brace expansion in bash

Everyone has done one of the following to make a quick backup of a file: $ cp filename filename-old $ cp filename-old filename These seem fairly straightforward, what could possibly make them more efficient? Let’s look at an example $ cp filename{,-old} $ cp filename{-old,} $ cp filename{-v1,-v2} Brace expansion can take place anywhere in […]

Read More
Scripting

Linux routing magic

Suppose you’re setting up a test environment, and you want a server to be able to handle some improbably large number of IP addresses, like a /16 or even larger. You could just write a script to add them all one at a time, or you could use this little shortcut and add the entire […]

Read More