Bash scripting: loops to automate everyday jobs


You have surely come across some tasks that you have to do repeatedly. For example, imagine that you have a directory full of files and you want to change the name of all of them, or that you need to compress several files or decompress them, perhaps you need to convert from one format to another, periodic backups, etc. Scripts have solutions for all this.

These tasks when applied to a single file in Bash are fine. The problem is when you have to apply it to dozens of them. Homework can be very annoying. With a simple loop or loop in Bash you could get rid of that problem and have a task run repeatedly to automate it and not cost you so much work. The way to do it is super simple, but many new users do not do it and end up doing the task manually or looking for graphic programs that do it ...

For that, stick with this structure:

for x in objetivo; do comando; done

By exampleSuppose you want to delete files named name0, name1, name2, name3, etc., up to the number name100. Going one by one with rm would be quite tedious, instead you can run the following command:

for n in 'seq 100'; do rm nombre$n; done

Or maybe imagine that you have a directory with several compressed .zip files that you want to extract. To avoid having to go one by one you can use:

<pre>for n in *.zip; do unzip "$n"; done

You can alter these bash loops as you prefer to use the tool you need in your case. For example, yet another, now imagine you want to unpack a tarball:

<pre>for n in *.tar.xz; do tar -xf "$n"; done</pre>

Hope that helps not to waste so much time doing all those tasks one by one and that you can apply this to streamline your daily work. As you can see, it has no mystery, it is super simple ...

The content of the article adheres to our principles of editorial ethics. To report an error click here!.

Be the first to comment

Leave a Comment

Your email address will not be published.



  1. Responsible for the data: AB Internet Networks 2008 SL
  2. Purpose of the data: Control SPAM, comment management.
  3. Legitimation: Your consent
  4. Communication of the data: The data will not be communicated to third parties except by legal obligation.
  5. Data storage: Database hosted by Occentus Networks (EU)
  6. Rights: At any time you can limit, recover and delete your information.