Create Custom Terminal Commands

I spent some time today building custom terminal commands and I thought I would write about two simple ways to create your own custom commands. Custom bash scripts are a great way to automate redundant tasks. The examples below will give you a simple starting point for developing your own custom bash scripts.

1 - Create a custom command inside of your bash profile. #

Open your terminal and type:

$ open ~/.bash_profile

This command will open up your bash profile. Inside of your bash profile you can write custom terminal commands using the syntax below.
ex:

to(){
  touch $1  
  open $1
}

Now in any directory you are in you can type the command:

$ to example.sh

This will create (touch) a new file and immediately open it.

2 - Add a custom shell script to your PATH #

Open your bash profile. (See above.) If the following line isn’t present inside of your bash profile then add it somewhere in your bash profile.

export PATH=$PATH":$HOME/bin"

That line adds the bin folder to your PATH variable. Now navigate to your /bin folder and create a new file. We’ll use our new command that we created above:

$ to hello.sh

This command created and opened an empty file called hello.sh. Now inside of hello.sh we will include a basic hello world script. Add the following code to hello.sh:

#!/bin/bash  
echo "Hello World!"

Now inside of your /bin directory type the following command into the terminal:

$ chmod +x hello.sh   

That command made it so that our shell script can be called and executed. (It changes the access permissions.)
Now from any directory you will get the following result:

$ hello.sh  
Hello World!

Now go make some custom scripts of your own!

edit: Make sure to restart your Terminal so that changes can take effect.

 
20
Kudos
 
20
Kudos

Now read this

Hack Reactor - How I Became a Hacker

“Hey Ben, what classes are you taking next semester?” “Actually, I’m not taking any classes. I’m taking the semester off to go live in San Francisco to go to a coding bootcamp. All of my money will be spent on tuition, I’ll be leaving... Continue →