Skip to content

Instantly share code, notes, and snippets.

@ulisesantana
Created May 2, 2021 09:48
Show Gist options
  • Save ulisesantana/a2e7f564099ab9d3ea1bc391fd127c92 to your computer and use it in GitHub Desktop.
Save ulisesantana/a2e7f564099ab9d3ea1bc391fd127c92 to your computer and use it in GitHub Desktop.
Generate a file with current day as file name based on template. Will create a folder based on current month and save the file inside.
#!/usr/bin/env bash
check() {
test "$@" && echo true || echo false
}
show_help() {
echo -e "Generate a file with current day as file name based on template. Will create a folder based on current month and save the file inside.\n"
echo -e "Usage: new-post.sh template_path output_parent_directory.\n"
echo -e "Example: ./new-post.sh ./template.md ./posts
Output:
📁 Creating directory ./posts/2021-05.
📝 Created new post ./posts/2021-05/2021-05-02.md."
}
create_folder_if_no_exists() {
directory_path=$1
directory_exists="$(check -d ${directory_path})"
if [[ $directory_exists == "false" ]] ; then
echo -e "📁 Creating directory ${directory_path}."
mkdir -p ${directory_path}
fi
}
create_post() {
template=$1
new_post=$2
file_exists="$(check -e ${new_post})"
if [[ $file_exists == "true" ]] ; then
echo -e "⚠️ Post ${new_post} already exists."
else
{
cp ${template} ${new_post} &&
echo -e "📝 Created new post ${new_post}."
} || {
echo -e "⚠️ Error creating new post."
}
fi
}
main() {
DEBUG=false
if [[ $1 == "--help" || $1 == "-h" ]] ; then
show_help
else
today=$(date '+%Y-%m-%d')
current_month=${today:0:7}
template="$(echo $1)"
template_extension=${template##*.}
output_directory="$(echo $2)/${current_month}"
new_post=${output_directory}/${today}.${template_extension}
create_folder_if_no_exists ${output_directory}
create_post ${template} ${new_post}
if $DEBUG ; then
echo "today = ${today}"
echo "current_month = ${current_month}"
echo "template = ${template}"
echo "template_extension = ${template_extension}"
echo "output_directory = ${output_directory}"
echo "new_post = ${new_post}"
fi
fi
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment