This is just me celebrating a small win. I’ve been slowly learning bash scripting, and just now I was able to quickly write a simple bash script to automate a file moving task without referring to my notes or the web!
It’s not a super complicated script, I’m just happy I’m starting to internalize the knowledge I’ve been building.
I’ve been organizing my media files after ripping our DVD collection. I had all the files for The Smurfs cartoon (love the Smurfs) in the main Smurfs show folder. I wanted to put them all into their respective season folders (Season.XX). Here’s the script:
#! /bin/bash
for number in {01..09}; do
find . -type f -name "The.Smurfs.S$number*" -exec mv {} Season.$number/ \;
done
I could have done it as a one liner, but I like to keep things like this for future reference.
It makes it usable without typing bash. Same would apply for a python script. For example you can make a python script named with no extension and add #!/usr/bin/python to the top of the file. Bash shell sees this and knows to execute the script using that python path.Then you just include the directory in your $PATH and chmod +x the script. Then you can type $python_script instead of $python python_script.py
Interesting. This particular script I’m just double clicking to run, but I did name it script.sh. If I were to run it in the terminal, I would just do ./script.sh
Yes. You’re correct. The script will execute with /bin/bash by default but only in a bash shell. #!/bin/bash is still a good habit to have. Some platforms may be running an “sh” shell by default. In this case if you ran the script it would execute with /bin/sh instead. Which would work or not work depending on if your script was written in purely sh syntax and not using any uniquely bash style syntax.
Bash can run all sh scripts but sh cannot run all bash scripts. So explicitly stating for which one your script was written for is good practice to not run into errors if you move your script to a different environment.