Executable awk scripts in Linux

Awk is a useful language for many command line tasks. Often awk is used on the command line on its own or with strings piped to it, but it is possible to turn that awk code into an executable script.

Consider the following script. This file contains awk code with a shebang of awk -f. The -f is important here; without it, the script won’t work. The code itself is the same as you would use on the command line.

#!/usr/bin/awk -f

# This code will print out the users who have bash as their default shell.


    if (substr($7, length($7)-3) == "bash")
        print $1, "is using", $7;

This script can then be called with an /etc/passwd style file to print the users who have bash as their default shell. For example:

$ ./passwd.awk /etc/passwd
root is using /bin/bash
tim is using /bin/bash

Leave a Reply

Your email address will not be published. Required fields are marked *