Skip to main content

Creating a bash script

Bash scripts are files containing code that tell your computer to do something.  In this instance, I want to rename a batch files in a directory.  Such as changing:
 

37351001 - BlueSpotted.jpg
37351008 -SpangledEmporer _ 0133A.jpg
37353003 -Black-Bream_3481 .jpg
37353004   -35 - Yellowfin.jpg

Instead having these files appear as:

37351001.jpg
37351008.jpg
37353003.jpg
37353004.jpg

However, I don't have four files.  Wouldn't be worth my time writing the script.  But for hundreds or thousands - definitely worth creating a script.

 

Bash scripts

Here’s how to make a bash script executable on a Mac.  I'll be creating a file called rename.sh.  Add the following line to the very top of your bash script, before any of the code:

#!/usr/bin/env bash

Make the script executable by changing the file permissions.  Run the following command using a Terminal application:

chmod +x {filename}

For me that will be

chmod +x rename.sh

Making a bash script clean up thousands of image files.

#!/usr/bin/env bash
cd /Users/andrewfletcher/Apps/tmp/images
for file in *.jpg; do
    mv -vn "${file}" "${file% -*}.jpg"
    mv -vn "${file}" "${file%-*}.jpg"
done
for file in *\ *; do
    mv "${file}" "${file// /}"
done

The first part looks for space and dash and then removes everything after this point.

This will go through all .jpg files in the current directory, renaming them to what you want.  The -v option to mv simply means to print the rename as it happens (useful to know that it's doing something), and the -n flag means don't accidentally overwrite any files (in case you type something in wrong or come across duplicate numbers).

The magic is happening in the ${file%-*}.jpg, which is instructing that everything is to be removed after the first - and add the .jpg back.  Also known as a 'shell parameter expansion'.

for file in *.jpg; do
    mv -vn "${file}" "${file% -*}.jpg"
    mv -vn "${file}" "${file%-*}.jpg"
done

The second part looks at how to replace/remove any spaces in file names:

for file in *\ *; do
    mv "${file}" "${file// /}"
done

The ${file// /} part utilizes bash's parameter expansion mechanism to replace a pattern within a parameter with the supplied string.

In this instance, spaces are removed.  However, if you wanted to replace your spaces with another character such as an underscore _ then you can use:

"${file// /_}"

 

Executing your bash script

Once written, to execute your script run the command

./rename.sh

 

Related articles

Andrew Fletcher06 May 2024
Exploring historical memory usage monitoring with Sysstat
In the realm of system administration and monitoring, understanding memory usage trends is crucial for maintaining system health and performance. While tools like htop offer real-time insights into memory usage, they lack the capability to provide historical data. So, what if you need to analyze...