AOG Poston
a software engineer

Creating custom commands for your terminal
by A.O.G Poston on 11/17/23

Ive started writing a bit more and instead of using a CMS or relying on a databse, I am using flatfiles and VSCode as a text editor. In order to do so, I am trading conveniences, one such convience is generating the date of publishing automatically. So, every time I post an article, I have to write the date in ISO-8601. There is a way to use the command line to generate the date. $ date +"%Y-%m-%dT%H:%M:%S%z"

That works fine but, in the spirit of creating value wherever we find the opportunity, lets build a script that can generate a date in the correct format and is only a single word.

Requirements

  • C++ Compiler
  • Unix based system

Create a script in C++

First create a file named 'isodate.cpp' and place it in your current working directory.

Then inside the isodate.cpp file, write the code:

#include <ctime>
#include <iostream>

int main(){
  time_t now;
  time(&now);
  char buf[sizeof "0000-00-00T00:00:00Z"];
  strftime(buf, sizeof buf, "%Y-%m-%dT%H:%M:%SZ", gmtime(&now));
  std::cout << buf << "\n";
  return 0;
}

This is a script written in cpp that displays the current date and time in ISO-8601.

Compile the C++ script into an executable.

Now that you have that script, generate an executable for your system by running the command.

To do on MAC, run the command: g++ isodate.cpp -o isodate

On Windows, gcc isodate.cpp -o isodate.exe

now if you run the executable from your terminal, isodate or isodate.exe you should see the terminal output the date Once you have the executable, move it to your executable directory and make it runable from any directory. Each operating system has a different directory where it stores common executables and to make this command runable anywhere. Windows is a little bit trickier, but its possible to set up this sort of thing by changing your Environment Variables. Im not going to cover that here.

On unix systems however you can find that folder by running:

echo $PATH

#output
#/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/share/dotnet:~/.dotnet/tools:/Library/Apple/usr/bin:/Library/Frameworks/Mono.#framework/Versions/Current/Commands

Each path name is seperated with a ":", and your system checks each of them for executables when you run commands in your terminal. Run ls -la <pick a directory> in your terminal and youll see commands you can try to run. The directory I chose for my script is /usr/local/bin

To move the file we just created into one of those directories run: sudo cp isodate /usr/local/bin/isodate

and after putting in my password, the file moved over and now when I write isodate and press entery in my terminal, I get the current time and date in the perfect format for these flatfiles. Saved myself a nano second and it was worth it.