Skip to content

Instantly share code, notes, and snippets.

@naranyala
Last active August 8, 2023 03:10
Show Gist options
  • Save naranyala/5a1f03d2cd69e2bf78c00a8e085e8843 to your computer and use it in GitHub Desktop.
Save naranyala/5a1f03d2cd69e2bf78c00a8e085e8843 to your computer and use it in GitHub Desktop.
this script simplify `mkdir` and `touch` and have clear state when create and removing file or directory
#!/bin/bash
# Function to print usage information
print_usage() {
echo "Usage: $0 [-O|--open] <file_path>"
}
# Check if an argument was provided
if [ $# -eq 0 ]; then
print_usage
exit 1
fi
# Initialize variables
open_file=false
# Option parsing loop
while [[ "$#" -gt 0 ]]; do
case "$1" in
-O | --open) open_file=true ;;
--) break ;; # End of options
-*)
echo "Error: Unknown option '$1'"
print_usage
exit 1
;;
*) filepath="$1" ;;
esac
shift
done
# Check if the filepath is empty
if [ -z "$filepath" ]; then
echo "Error: File path cannot be empty."
print_usage
exit 1
fi
# Check if the file already exists
if [ -e "$filepath" ]; then
echo "Error: The file '$filepath' already exists."
exit 1
fi
# Create the directory if it doesn't exist
mkdir -p "$(dirname "$filepath")"
# Create the file
touch "$filepath"
# Display success message
echo "File '$filepath' created successfully."
# Open the file in Neovim if the "--open" option is present
if [ "$open_file" = true ]; then
nvim "$filepath"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment