Skip to content

Instantly share code, notes, and snippets.

@StoyPenny
Last active February 1, 2025 22:41
Show Gist options
  • Save StoyPenny/c2154c3e24e6d944b88204f69ed28761 to your computer and use it in GitHub Desktop.
Save StoyPenny/c2154c3e24e6d944b88204f69ed28761 to your computer and use it in GitHub Desktop.
New Bash Command Making Script

New Bash Command Making Script

This is a simple script that makes the process of creating new bash commands easier.

After you get setup quickly, simply run the new-bash-script in your terminal and give an an argument of what you want the file and command to be called. This will then generate file in the right directory, make it executable, and then open a nano window for you to copy and paste your script or start writing from scratch. You may need to open a new terminal window after adding a new command so that it is registered in the terminal window.


Setting Things Ups

Create a new file

sudo touch "/usr/local/bin/<REPLACE_WITH_YOUR_COMMAND_NAME>" 

Make the file executable

sudo chmod +x /usr/local/bin/<REPLACE_WITH_YOUR_COMMAND_NAME>

Open the file in nano editor

Open the file in the editor of your choice, we are using nano here as an example. Once the editor is open you will copy and paste the script in the next section.

sudo nano /usr/local/bin/<REPLACE_WITH_YOUR_COMMAND_NAME>

The Script

#!/bin/bash

# Check if an argument is provided 
if [ -z "$1" ]; then 
	echo "Please provide a file/command name as an argument." 
	exit 1 
fi

# Clean the filename 
echo "Making sure you your file name is formatted properly if you forgot to"
filename=$(echo "$1" | sed -e 's/[^[:alnum:]]/_/g' | tr -d ' ' | tr ' ' '-' | tr -d '_')

# Check if the file already exists 
echo "Checking if this function already exists.."
if [ -f "$filename" ]; then 
	echo "File '$filename' already exists." 
	exit 1 
fi

# Create the file 
echo "Creating new file at: /usr/local/bin/$1"
sudo touch "/usr/local/bin/$1" 

# Make it executable:
echo "Making the file executable.."
sudo chmod +x /usr/local/bin/$1

# Open the file in nano editor 
sudo nano "$1"

echo "Your script is ready to use, simply run this command in a new terminal window:
new-bash-script $1"

Usage

Create Your New Command

new-bash-script <YOUR_NEW_SCRIPT_NAME>

# Example: new-bash-script file-backups

Use Your New Command

<YOUR_NEW_SCRIPT_NAME> <ARGUMENTS_FOR_YOUR_COMMAND>

# Example: file-backups /my/files/to/backup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment