Script to clean these duplicates from ~/.zshrc
- User
Script to clean these duplicates from ~/.zshrc
- Assistant
Certainly! Below is a Bash script that removes duplicate lines from your
~/.zshrcfile while preserving the original order of lines. The script also creates a backup of your original~/.zshrcbefore making any changes, ensuring that you can easily restore it if needed.Script:
clean_zshrc.shbash#!/bin/bash # ----------------------------------------------------------------------------- # Script Name: clean_zshrc.sh # Description: Removes duplicate lines from ~/.zshrc while preserving order. # Creates a backup of the original ~/.zshrc before making changes. # Usage: Make the script executable and run it. # ----------------------------------------------------------------------------- # Define variables ZSHRC="$HOME/.zshrc" BACKUP_DIR="$HOME/.zshrc_backups" TIMESTAMP=$(date +"%Y%m%d_%H%M%S") BACKUP_FILE="$BACKUP_DIR/.zshrc.backup_$TIMESTAMP" # Function to display messages function echo_info() { echo -e "\033[1;34m[INFO]\033[0m $1" } function echo_warning() { echo -e "\033[1;33m[WARNING]\033[0m $1" } function echo_error() { echo -e "\033[1;31m[ERROR]\033[0m $1" } # Check if ~/.zshrc exists if [[ ! -f "$ZSHRC" ]]; then echo_error "~/.zshrc does not exist. Exiting." exit 1 fi # Create backup directory if it doesn't exist if [[ ! -d "$BACKUP_DIR" ]]; then mkdir -p "$BACKUP_DIR" if [[ $? -ne 0 ]]; then echo_error "Failed to create backup directory at $BACKUP_DIR. Exiting." exit 1 fi echo_info "Created backup directory at $BACKUP_DIR." fi # Create a backup of ~/.zshrc cp "$ZSHRC" "$BACKUP_FILE" if [[ $? -ne 0 ]]; then echo_error "Failed to create backup of ~/.zshrc. Exiting." exit 1 fi echo_info "Backup of ~/.zshrc created at $BACKUP_FILE." # Remove duplicate lines while preserving the original order # Explanation: # - `awk '!seen[$0]++'` prints only the first occurrence of each line. awk '!seen[$0]++' "$ZSHRC" > "${ZSHRC}.tmp" # Verify that awk succeeded if [[ $? -ne 0 ]]; then echo_error "Failed to process ~/.zshrc with awk. Exiting." exit 1 fi # Replace the original ~/.zshrc with the cleaned version mv "${ZSHRC}.tmp" "$ZSHRC" if [[ $? -ne 0 ]]; then echo_error "Failed to replace ~/.zshrc with the cleaned version. Exiting." exit 1 fi echo_info "Duplicates have been removed from ~/.zshrc successfully." # Optional: Reload zsh configuration echo_info "Reloading zsh configuration..." source "$ZSHRC" echo_info "Cleanup complete."