Bash Programming

bash script: Code Snippet Manager Script


#!/bin/bash

# Associative array to store code snippets
declare -A snippets

# Function to add a new code snippet
add_snippet() {
echo "Enter the snippet key:"
read key
echo "Enter the code snippet:"
read code
snippets[$key]="$code"
echo "Snippet added successfully!"
}

# Function to search for a code snippet
search_snippet() {
echo "Enter the snippet key to search:"
read key
if [[ -v snippets[$key] ]]; then
echo "Snippet found:"
echo "${snippets[$key]}"
else
echo "Snippet not found!"
fi
}

# Main menu for the script
while true; do
echo "Code Snippet Manager"
echo "1. Add a new snippet"
echo "2. Search for a snippet"
echo "3. Exit"
read -p "Select an option: " choice

case $choice in
1) add_snippet ;;
2) search_snippet ;;
3) echo "Exiting..."; break ;;
*) echo "Invalid option. Please try again." ;;
esac
done

The bash script provided is a Code Snippet Manager that allows users to add new code snippets and search for existing ones. Here’s a breakdown of the script:

1. An associative array named `snippets` is declared to store the code snippets. The keys are used to identify each snippet.

2. The `add_snippet` function prompts the user to enter a snippet key and the code snippet itself. The key-value pair is then added to the `snippets` array.

3. The `search_snippet` function asks the user for a snippet key to search for. If the key exists in the `snippets` array, the corresponding code snippet is displayed.

4. The main menu is displayed in a loop, allowing the user to choose from the following options:
– Add a new snippet
– Search for a snippet
– Exit the script

5. Depending on the user’s choice, the corresponding function is called. If an invalid option is selected, an error message is displayed.

This script provides a simple way to manage and retrieve code snippets using a command-line interface.