BASH script to copy and rename MARC records

I’ve been finishing up a project that requires a MARC record to be copied into 2 different locations and renamed based on directory names.

This script was written and tested on Windows 7 in Cygwin using the BASH Shell.

#!/bin/bash

# copy_marc_records.sh
# BASH script to copy MARC records from 'MARC-records' directory
# into correct directories in '4.toAccess_needsMARC' and
# '4a.toPreservation_needsMARC' and rename the MARC record
# to match the directory name of that item

# local directory paths
marc_path="./MARC-records/"
toAccess_path="./4.toAccess_needsMARC/"
toPreservation_path="./4a.toPreservation_needsMARC/"

# list of paths to process
paths_to_process="$toAccess_path $toPreservation_path"

# Start loop1: BASH will split a variable on spaces if it's not in double-quotes
for path in $paths_to_process; do

    echo "$path"

    # Start loop2: for first path
    for dir in $path*/; do

        echo "$dir"

        # Start if1: check if dir does not exist
        if [[ ! -e "$dir" ]]; then
            echo "****************"
            echo "$dir does not exist"

        # check if dir is not a directory
        elif [[ ! -d "$dir" ]]; then
            echo "*****************"
            echo "$dir is not a directory"

        # run commands
        else
            # example $dir: ./4.toAccess_needsMARC/CRLA_1982-03_486/

            # remove trailing slash: ./4.toAccess_needsMARC/CRLA_1982-03_486
            item_name=${dir%/}

            # remove everything before CRLA: CRLA_1982-03_486
            item_name=${item_name#*_needsMARC/}

            # get the number for the MARC record: 486
            marc_number=${item_name#CRLA_*_}

            # MARC records in marc_path named: 486.mrc
            marc_record=$(printf "%s.mrc" "$marc_number")

            # Start if2: check if marc_record does not exist
            if [[ ! -e "$marc_path""$marc_record" ]]; then
                echo "**********************"
                echo "$marc_record does not exist for $item_name"
            
            else
                # copy MARC record to $dir in $path
                cp "$marc_path""$marc_record" "$dir"

                # rename MARC record
                mv "$dir""$marc_record" "$dir"$(printf "%s.mrc" "$item_name")
            
            # End if2
            fi
        
        # End if1
        fi

    # End loop2
    done

# End loop1
done

Jeremy Moore

jeremy.moore@txstate.edu