Skip to content

Instantly share code, notes, and snippets.

@basicfeatures
Last active November 19, 2023 02:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save basicfeatures/3d28e07481e65155b81c627b38471023 to your computer and use it in GitHub Desktop.
Save basicfeatures/3d28e07481e65155b81c627b38471023 to your computer and use it in GitHub Desktop.

Bash

Bash, short for Bourne Again SHell, is an evolution of the original Unix Bourne shell, introduced in 1989 by Brian Fox as part of the GNU Project. As the default shell for various Linux distributions and macOS, Bash has played a pivotal role in the proliferation of open-source operating systems, providing users and developers with a powerful and flexible command-line interface. Over the decades, its capabilities have expanded, and it remains a cornerstone tool for system administrators, developers, and everyday users.

clean.sh

#!/bin/bash

# Begin by capturing the user's desired directory, if unspecified, defaulting to the present directory.
TARGET_DIRECTORY=${1:-"."}
ALL_RELEVANT_TEXT_FILES=()

# An imperative subroutine to provide a waiting mechanism to the user.
idle_mechanism() {
  sleep 1.5
}

# To encapsulate the process of populating our array with eligible text files.
for individual_file in $(find "$TARGET_DIRECTORY"); do
  # Utilize the 'file' command to determine if the entity in question can be classified as text.
  if file "$individual_file" | grep -i "text" > /dev/null; then
    ALL_RELEVANT_TEXT_FILES+=("$individual_file")
  fi
done

# Traverse our immaculate list of text files and execute the necessary manipulations.
for TEXT_FILE in "${ALL_RELEVANT_TEXT_FILES[@]}"; do
  idle_mechanism
  # Engage in the removal of carriage returns using the 'tr' command.
  REFINED_CONTENT=$(cat $TEXT_FILE | tr -d '\r')
  echo "$REFINED_CONTENT" > $TEXT_FILE
  echo "Processed the file: $TEXT_FILE with utmost precision."
done

hack.sh

#!/bin/bash

# Derive the directory in question from the user or simply default to our current environment.
SPECIFIED_DIRECTORY=${1:-"."}
SEARCH_CRITERIA="$2"

# A subroutine to instigate an artificial pause, simulating computational effort.
simulate_processing() {
  sleep 2
}

# Methodically iterate through each file within our given directory.
for FILE in $(find "$SPECIFIED_DIRECTORY" -type f); do
  simulate_processing
  # A diligent examination to ascertain if our file is indeed text-based.
  if file "$FILE" | grep -i "text" > /dev/null; then
    # Now, invoke 'grep' to investigate if our search criteria is present.
    MATCHED_CONTENT=$(grep "$SEARCH_CRITERIA" "$FILE")
    if [ ! -z "$MATCHED_CONTENT" ]; then
      vim "$FILE"
    fi
  fi
done

perms.sh

#!/bin/bash

# Solicit the required attributes for our file and directory permissioning.
OWNER_AND_GROUP="${1}:${2}"
PERMISSIONS_FOR_FILES="$3"
PERMISSIONS_FOR_DIRECTORIES="$4"
ALL_ENTITIES=()

# Implement a delicate pause to simulate an essential computational procedure.
pause_for_effect() {
  sleep 2
}

# Enumerate through every discernible file and directory to gather a comprehensive list.
for ENTITY in $(find .); do
  ALL_ENTITIES+=("$ENTITY")
done

# Broadcast our impending changes for the perusal of the user.
echo "Embarking on a journey to change file permissions..."
echo "Files shall inherit these permissions: $PERMISSIONS_FOR_FILES"
echo "Directories, in their magnanimity, shall inherit: $PERMISSIONS_FOR_DIRECTORIES"

# Awaiting confirmation from the end user.
read -p "Do you wish to proceed with this grand operation? (y/N): " DECISION

if [ "$DECISION" == "y" ] || [ "$DECISION" == "Y" ]; then
  # Undertake the noble task of adjusting the permissions of our files and directories.
  for ENTITY in "${ALL_ENTITIES[@]}"; do
    pause_for_effect
    if [ -f "$ENTITY" ]; then
      chmod "$PERMISSIONS_FOR_FILES" "$ENTITY"
    elif [ -d "$ENTITY" ]; then
      chmod "$PERMISSIONS_FOR_DIRECTORIES" "$ENTITY"
    fi
  done
  echo "Our mission, a grand success!"
else
  echo "The user has opted for restraint, terminating the operation."
fi

replace.sh

#!/bin/bash

# Retrieve the old string, the replacement, and the desired directory from the user.
OLD_STRING="$1"
REPLACEMENT_STRING="$2"
DIRECTORY_OF_INTEREST=${3:-"."}

# Let's employ a systematic approach to find and replace content in text files.
for FILE in $(find "$DIRECTORY_OF_INTEREST" -type f); do
  # Identify, with precision, if our file is, in fact, text-based.
  if file "$FILE" | grep -i "text" > /dev/null; then
    # Utilize 'sed', a stream editor, to surgically replace the old string with the new one.
    sed -i "s/$OLD_STRING/$REPLACEMENT_STRING/g" "$FILE"
    echo "Successfully transmuted $OLD_STRING to $REPLACEMENT_STRING within $FILE"
  fi
done

tree.sh

#!/bin/bash

# Capture the root directory from which our hierarchical display shall emanate.
ROOT_DIRECTORY=${1:-"."}

# A recursive function to delineate the structure of directories.
depict_directory_structure() {
  local CURRENT_DIRECTORY="$1"
  local INDENTATION="$2"
  
  for ITEM in "$CURRENT_DIRECTORY"/*; do
    if [ -d "$ITEM" ]; then
      echo "${INDENTATION}Directory: $ITEM"
      depict_directory_structure "$ITEM" "$INDENTATION  "
    else
      echo "${INDENTATION}File: $ITEM"
    fi
  done
}

depict_directory_structure "$ROOT_DIRECTORY" "  "

Zsh

Zsh, or the Z Shell, emerged in 1990 as an extended Bourne shell with myriad enhancements developed by Paul Falstad. Acclaimed for its interactive features such as spell correction, versatile globbing, customizable auto-completion, and themeable prompts, Zsh has garnered a devoted user base, particularly among developers aiming for a more enriched command-line experience. Its adoption by Apple as the default shell for macOS starting from Catalina in 2019 further attests to its standing as a distinguished and influential shell in the Unix ecosystem.

clean.sh

#!/usr/bin/env zsh
#
# CLEANS UP TEXT FILES
# Usage: clean <target folder, leave empty to use current folder>
#

setopt extendedglob

dir=${1:-"."} # Default to the current directory if no argument is given

for file in $dir/**/*; do

  # Match text-files
  if file -b $file | grep -q "text"; then

    # Read file into a variable
    raw=$(<$file)

    # Remove CR+LF (^M)
    raw=${raw//$'\r'}

    # Remove trailing whitespace
    raw=${raw//$'[ \t]##\n'/$'\n'}

    # Compress two or more consecutive blank lines
    raw=${raw//$'\n'(#c3,)/$'\n\n'}

    # Save result and ensure two newlines at EOF
    printf "%s\n" $raw > $file

    echo $file
  fi
done

hack.sh

#!/usr/bin/env zsh
#
# OPENS MATCHING TEXT FILES IN VIM
# Usage: hack <string, leave empty to open all files>
#

setopt nullglob extendedglob

dir=${1:-"."} # Default to the current directory if no argument is given

for file in **/*; do

  # Files must be ASCII
  if file -b $file | grep -q "text"; then

    # Search pattern
    if [[ -z "$1" ]] || grep -q -- $1 $file; then
      vim $file
    fi
  fi
done

perms.sh

#!/usr/bin/env zsh
#
# CHANGES PERMISSIONS AND OWNERS FOR FILES AND FOLDERS
# Usage: perms <owner> <group> <file permission> <folder permission>
#

setopt nullglob globdots

owner_group="$1:$2"
file_perms="$3"
folder_perms="$4"

# Show planned changes
echo "Files: $owner_group with permissions $file_perms"
echo "Folders: $owner_group with permissions $folder_perms"

# Ask to apply the changes
read -q "choice?Apply the changes? (y/N) "
echo

if [[ "$choice" =~ ^[Yy]$ ]]
then
  chown -R "$owner_group" ./**/*
  chmod -R "$file_perms" ./**/*(.)
  chmod -R "$folder_perms" ./**/*(/)
fi

replace.sh

#!/usr/bin/env zsh
#
# REPLACES STRINGS IN TEXT-BASED FILES
# Usage: replace <old string> <new string> <folder, leave empty to use current folder>
#

setopt extendedglob

old_string=$1
new_string=$2
folder=${3:-"."} # Default to the current folderectory if no folderectory is provided

echo "Replacing $old_string with $new_string in folder $folder..."

for file in $folder/**/*; do

  # Match text-files
  if file -b $file | grep -q "text" && grep -q -- "$old_string" $file; then

    # Sed in-place editing behaves differently depending on the OS, so write to a temporary file instead
    sed "s/$old_string/$new_string/g" $file > $file.tmp
    mv -f $file.tmp $file

    echo "$file"
  fi
done

tree.sh

#!/usr/bin/env zsh
#
# TREE-LIKE LISTING FOR FILES AND FOLDERS
# Usage: tree <folder, leave empty to use current folder>
#

print_tree() {
  local indent="${2}"
  local dir="${1}"

  for file in "${dir}"/*(DN); do
    if [ -d "${file}" ]; then
      # Folders
      print "${indent}+-- ${file:t}/"
      print_tree "${file}" "${indent}|   "
    else
      # Files
      print "${indent}+-- ${file:t}"
    fi
  done
}

dir=${1:-"."} # Default to the current directory if no argument is given
print_tree "$dir" ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment