5 Bash for loop examples to make command line tasks more efficient

One of the things that excited me while learning Unix/Linux was how quickly one can perform tasks via the command line. Bash is a fully functional scripting language that incorporates Variables, Loops and If/Then statements; the bash shell allows a user to use these functions while performing adhoc tasks via the command line. This is also true for the other common shells such as bourne, korn shell, and csh. Below I will show 5 example for loops that are run on the command line without being placed into a shell script.

Grepping a file without using cat, and other grep tricks

The grep command is a command that most Linux users learn early on, and many times they learn to use it via pipes (stdin). Because of this some Linux users just assume that grep can only be used with stdin; it's ok, I was one of those too! Before I continue with some grep tricks I want to clarify the basic grep usage. Stop Doing This: $ cat file.log | grep "something" something Do This More:

SSH: Disable Host Checking for Scripts & Automation

In the world of Cloud Servers and Virtual Machines scripting and automation are top priority for any sysadmin. Recently while I was creating a script that logged into another server via SSH to run arbitrary commands, I ran into a brick wall. $ ssh The authenticity of host ' (' can't be established. ECDSA key fingerprint is 74:39:3b:09:43:57:ea:fb:12:18:45:0e:c6:55:bf:58. Are you sure you want to continue connecting (yes/no)? To anyone who has used SSH long enough the above message should look familiar.

Unix Shell: The Art of I/O Redirection

One of the primary tricks in my sysadmin bag-o-tricks is Input/Output Redirection; I have found that while many people use Shell I/O Redirection throughout their day not everyone fully understands why and how it works. The Input and Output In the Unix environment there is always 3 streams open stdin, stdout, & stderr; these special streams are used for interacting with the user input and program output within the Unix/Linux shell environment.

bash: Field Separator Variable

By default when using a for loop in bash the field separator is set to a space. Example: [[email protected] ~]$ for x in list:like:this; do echo $x; done list:like:this One of the cool things about bash is that you can change this by setting a simple variable $IFS [[email protected] ~]$ IFS=":" [[email protected] ~]$ for x in list:like:this; do echo $x; done list like this

Bash: Repeated tasks with seq and for loops

There comes a time where every sysadmin needs to execute the same task multiple times. Whether you need to create 12,000 2MB files, create multiple users, or simply delete more then 50k files at a time; for loops will save you time and typing. For the instances where you need to execute a for loop a specific amount of times you can use seq to your advantage. Today's example will show you how to create multiple files.