I've recently started learning bash due to my new job in a VFX company. We backup all of our media to LTO tapes (one master and one clone). I was tasked with writing a script that split the tape list of master and clone to a CSV file. I feel I've done so in a crude manner as this was my first ever script and would love some feedback as to how I could improve the efficiency / syntax / code in general so I can learn from this experience.
Here is the text file: https://1drv.ms/t/s!AkWewdosAYGuhiaBbehlLBF64Qsg
I've been executing the script by calling it like this:
$ sh /scriptname.sh filename.txt
#!/bin/bash # This script will split the presstore list of tapes into a .CSV file with two seperate coloumns. file="$1" echo "Splitting tape list....." touch tempsplit.csv #creates temporary file for use later in script while IFs= read line do lastchar=$(echo $line | tail -c 2) if [ "$lastchar" == : ] #Ommits any lines that end with : else error then echo -ne elif [ "$lastchar" -ge 0 -a "$lastchar" -le 9 ] #Selects lines that end in number then breakdown=$(echo "$line" | cut -d':' -f2,6) #selects fileds 2 & 6 containing tape numbers master=$(echo "$breakdown" | cut -d'a' -f1) #cuts first number clone=$(echo "$breakdown" | cut -d':' -f2) #cuts second number final=$(echo -e "$master,$clone" | tr -d ' ' >> tempsplit.txt) #outputs to a temp csv file fi done < $file touch tapelist_split.csv awk 'NR % 2 == 0' tempsplit.txt | sort -n >> tapelist_split.csv #removes every 2nd line, sorts numerically, converts to a .CSV file rm -rf tempsplit.txt #removes tempfile echo "Complete"
I'm not sure why the while read statement doesn't work if I don't call
file="$1" as in line 3 and again output to that varaible in line 20
done < $file- an explanation on this would be amazing.
I realise I shouldn't have to call my first if statement, as I only care about the numbers but if I don't I get an error: "integer expected" when I run the script - does anyone know why this might be.
The reason I create the file "tempslipt.txt" is because my code to remove every 2nd line and sort the file wasn't working within the wile read statement so I figured this was a clean way of doing it.
My code may not be very efficient or good which is why I'm asking for tips on how I can refine and correct it so in future I can write much cleaner scripts.