When the same commands repeat for the third time, it is time to write a script. A script is just a text file with the execute bit (file-permissions +x) and a shebang on the first line. When the kernel sees such a file, it starts the named interpreter as a new process-and-pid and feeds it the rest of the lines.
This lesson covers the skeleton that travels from script to script: shebang, variables, arguments, guard options, conditions, a loop over the lines of a file. The overview article with all the idioms is bash-scripting.