Automating actions in Nautilus (GNOME's file manager) with scripts

I often want to add today’s date to the beginning of a document’s name.

This is a simple way of keeping documents in temporal order, without resorting to a file management system, or using the “modification” view in Nautilus, GNOME’s file manager.

It’s possible to copy-and-paste the file, then rename it (to remove the “(copy)” from the end and the old date from the beginning, and then add the date to the beginning.

But it is tedious, and I have to do this loads, so I finally got round to automating it.

Here’s what I did.

Adding scripts to Nautilus

To add a script to Nautilus, put it in ~/.local/share/nautilus/scripts.

All scripts in that directory appear in the right-click context menu when you select one or more files in Nautilus:

Screenshot of Nautilus, showing the context menu for a file, on the “Scripts” sub-menu, showing a script called “Copy and redate”

The name showing in the context menu is the script’s name. (I’ve since changed “redate” to “re-date”.)

A script to prepend today’s date to a file

Here’s the script I’m using to achieve the task.

It is not perfect, but it should do what I need most of the time.


#!/bin/bash
# Script to add today's date to the beginning of a file name, removing the old date if there is one


TODAY="$(date -I)"


# get list of files selected in Nautilus as a string separated by newline characters

SELECTEDFILES="$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS"


strip_old_date() {

	# Check if something approximating a date is present at the beginning of the filename and remove


	if [[ "$OLDFILE" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2} ]]; then

		NEWFILE="$TODAY"_"${OLDFILE:10}"


	elif [[ "$OLDFILE" =~ ^[0-9]{8} ]]; then


		NEWFILE="$TODAY"_"${OLDFILE:8}"

	else
		NEWFILE="$TODAY"_"$OLDFILE"

	fi

}

sanitise_name() {

	# replace all spaces with underscores

	NEWFILE=$(sed -r 's/( +)/_/g' <<< "$NEWFILE")

	# remove all repeated consecutive underscores

	NEWFILE=$(sed -r 's/(_+)/_/g' <<< "$NEWFILE")
}

check_and_copy() {

	# if the intended new file name is already used, warn and do not copy

	if [ ! -f "$NEWFILE" ]; then

		cp "$OLDFILE" "$NEWFILE"

	else

		notify-send "File exists" ""$NEWFILE" already exists" --icon=dialog-warning

	fi
}


# read list of files into array, then process each file

readarray -t files_array <<< "$SELECTEDFILES"

for FILES in "${files_array[@]}"
do

	OLDFILE="$(basename "$FILES")"

	strip_old_date

	sanitise_name

	check_and_copy

done

I then made it executable (chmod 744 script_name).

I haven’t found a way to send an alert within Nautilus, so I resorted to using notify-send to warn when the action would overwrite an existing file.