Tuesday, February 25, 2014

Protip #2: Using loops from the commandline

Remember that the same things you can do in a shell script, you can also do directly from the command line. This includes looping constructs like for, while, and until. In a shell script you might write:

#!/bin/bash
for f in /home/user/Documents/*; do
    new=${f// /-}
    mv "$f" "$new"
done


to rename all of the files in your Documents folder, replacing spaces with hyphens (note that the parameter expansion, ${f// /-}, is not portable). But for something this simple, you don't need to write a script, you can just type this in on the command line, like this:

for f in /home/user/Documents/*
do new=${f// /-}
mv "$f" "$new"
done


or on one line:

for f in /home/user/Documents/*; do new=${f// /-}; mv "$f" "$new"; done

The indentation is irrelevant to the interpreter, we just use indentation in shell scripts for human readability. Those of you who have worked with a programming language with an interactive toplevel, such as Lisp or Python, may recognize how handy this is. Of course, many of you already know this and probably just went, "Duh!", but someone out there either didn't realize they could use loops from the command line, or just didn't really think of it because we usually see them in scripts. That person, upon reading this, was enlightened.1

No comments:

Post a Comment