Skip to content

Instantly share code, notes, and snippets.

@Ocean-Moist
Created October 22, 2024 06:56
Show Gist options
  • Select an option

  • Save Ocean-Moist/68ce4ea771314d7d96aba0ed12c68cea to your computer and use it in GitHub Desktop.

Select an option

Save Ocean-Moist/68ce4ea771314d7d96aba0ed12c68cea to your computer and use it in GitHub Desktop.
#!/bin/bash
# Script Name: create_project_file.sh
# Description: Creates a file with the specified path and content.
# Usage: ./create_project_file.sh
# Then paste the content with the first line as the file path (prefixed with //), followed by the file content.
# Finish input with Ctrl+D (EOF)
# Function to display usage instructions
usage() {
echo "Usage: ./create_project_file.sh"
echo "Then paste the content with the first line as the file path (prefixed with //), followed by the file content."
echo "Finish input with Ctrl+D (EOF)"
exit 1
}
# Check if the script is being run interactively
if [ ! -t 0 ]; then
echo "Error: This script expects interactive input."
usage
fi
echo "Paste your content below. Ensure the first line specifies the file path prefixed with '//'."
echo "Press Ctrl+D when you're done."
# Read the first line to get the file path
read -r first_line
# Check if the first line starts with //
if [[ "$first_line" != //* ]]; then
echo "Error: The first line must specify the file path prefixed with '//'."
exit 1
fi
# Extract the file path by removing the leading //
file_path=$(echo "$first_line" | sed 's|^// *||')
# Validate that the file path is not empty
if [ -z "$file_path" ]; then
echo "Error: File path is empty."
exit 1
fi
# Create the necessary directories
dir_path=$(dirname "$file_path")
mkdir -p "$dir_path"
# Inform the user about the file creation
echo "Creating file: $file_path"
# Write the remaining input to the file
# Use a temporary file to capture the remaining input
temp_file=$(mktemp)
# Read the rest of the input into the temporary file
cat > "$temp_file"
# Move the temporary file to the desired file path
mv "$temp_file" "$file_path"
# Set appropriate permissions (optional)
chmod 644 "$file_path"
echo "File '$file_path' has been created successfully."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment