Closed Captioning Closed captioning available on our YouTube channel

How to run command loops: Linux Tip

Network World | Mar 28, 2019

Being able to run command loops is one of the features of Linux that makes it easy to automate repetitive tasks. In this 2-minute Linux tip, learn about looping -- in scripts and on the command line.

Copyright © 2019 IDG Communications, Inc.

Similar
Hi, this is Sandra Henry-Stocker, author of the “Unix as a Second Language” blog on NetworkWorld.
In this 2-minute Linux tip, I want to talk about looping in scripts and on the command line. Being able to run command loops is one of the features of Linux that makes it easy to automate repetitive tasks.
I’m going to call the simplest type of for loop the explicit loop because I’m telling the command exactly what values to loop on. For example, “for values 1 2 3”. Here’s an example:
In this example, we specified the months we want to loop through and, for each month, we used a cal (calendar) command to figure out the last date in each month – by ignoring output lines that don’t contain a digit and grabbing only the last field on the last line. The output looks like this:
The next type of loop I’ll call the range loop. In this example, we loop through a range of values – both numeric and alphabetic.
The next form I’m going to call this argument-driven loop because the output depends on what arguments are provided to the script when it’s run – not when the script is written.
The $* refers to the string of arguments provided when the script is run.
The last type of for loop I’m going to call the dependent loop because the output changes depending on the output of the command that it runs. In this script, the output depends on what accounts are included in the /home directory.
This for loop generates a list of users by looking at home directories, uses the last command to see when each user last logged in and then shows only the most recent login (head -1) or the word “none” if the user hasn’t logged in recently enough to be included in the output of the last command.
Note that you can use the for loop on the command line as well as in scripts. I could use a for loop like this to display the /etc/passwd entry for each user with a home directory on this system.

That’s your Linux tip for today. If you have questions or would like to suggest a topic, please add a comment below. And don’t forget to subscribe to the IDG Tech(talk) channel.
If you liked this video, please hit the like and share buttons. For more Linux tips, be sure to follow us on Facebook, YouTube and NetworkWorld.com.
Popular
Featured videos from IDG.tv