scripting repetitive commands

i’ve recently become aware of how to make and write scripts, which honestly is just lovely. it makes running things for an idiot like me very, very user friendly. scripts are essentially an order-sensitive list of commands for your shell to execute when you ask it to, so they’re very versatile.
if, like me, you only have a vague idea what you are doing, here’s a few small things which you may find helpful.

  • find an editor you like and stick with it. notepad++ is a great one for various reasons, not least that you can format what you’re writing based on the language you are writing it in, which can make errors nice and easy to spot.
    • hint: shell script has its own language setting in the format menu.
  • if writing a linux/unix script on windows, note that windows characterizes line endings differently than unix, which invariably results in this: /bin/bash^M: bad interpreter on execution.
    this can be fixed in notepad++ by right clicking the line terminator picker in the bottom right Windows (CR LF) and switching it to Unix (LF)
  • can’t run your script? you probably didn’t make it executable. try chmod +x /path/to/
  • using a script to run an executable? you need to include the full path, so if you’re used to running systemctl status myApp you’ll instead have to write /bin/systemctl status myApp
    • don’t know where your executable is? try which myApp to ask the system to show you where it’s located.
  • all executable scripts must start with #!/bin/bash (dependant on environment, usually similar). this tells the executor what to use to execute it.
  • want your script to tell you what it’s doing as it’s doing it? make the first line in your script set -xv
  • because scripts are essentially lines of commands, they can operate and run commands in reference to a folder, like you can execute commands inside a folder. this means you can include a cd command to move to a particular directory in order to run a particular command in context of that directory.
  • got your scripts somewhere and want to be able to run them directly from the terminal? open /home/youruser/.profile in your text editor of choice and add this line at the end: export PATH=$PATH:/path/to/your/scripts

Leave a Reply

Your email address will not be published. Required fields are marked *