3 # bash-notes © 2023 by danix is licensed under CC BY-NC 4.0.
4 # To view a copy of this license, visit http://creativecommons.org/licenses/by-nc/4.0/
6 # to debug the script run it like:
7 # DEBUG=true notes.sh ...
8 # and check /tmp/debug_bash-notes.log
9 if [[ $DEBUG == true
]]; then
10 exec 5> /tmp
/debug_bash-notes.log
17 BASENAME
=$
( basename "$0" )
21 DBVERSION
=${VERSION}_
${NOW}
26 EDITOR
=${EDITOR:-/usr/bin/vim}
27 TERMINAL
=${TERMINAL:-/usr/bin/alacritty}
28 # Git binary only used if $USEGIT is true - See below
29 GIT
=${GIT:-/usr/bin/git}
30 # add options for your terminal. Remember to add the last option to execute
31 # your editor program, otherwise the script will fail.
32 # see example in the addnote function
33 TERM_OPTS
="--class notes --title notes -e "
34 # Setting PAGER here overrides whatever is set in your default shell
35 # comment this option to use your default pager if set in your shell.
36 PAGER
=${PAGER:-/usr/bin/more}
38 # set this to true to have output in plain text
39 # or use the -p option on the command line before every other option
41 # base directory for program files
42 BASEDIR
=${BASEDIR:-~/.local/share/bash-notes}
43 # notes database in json format
45 # directory containing the actual notes
46 NOTESDIR
=${BASEDIR}/notes
50 # If you want to store your notes in a git repository set this to true
52 # Address of your remote repository
53 GITREMOTE
=${GITREMOTE:-""}
54 # How long should we wait (in seconds) between sync on the git remote. Default 3600 (1 hour)
55 GITSYNCDELAY
=${GITSYNCDELAY:-"3600"}
56 # The name of this client. Defaults to the output of hostname
57 GITCLIENT
=${GITCLIENT:-""}
59 } # end set_defaults, do not change this line.
63 # Do not edit below this point
64 RCFILE
=${RCFILE:-~/.config/bash-notes.rc}
67 if [ ! -x "$JQ" ]; then
68 echo "jq not found in your PATH"
69 echo "install jq to continue"
73 # IMPORT USER DEFINED OPTIONS IF ANY
74 if [[ -f $RCFILE ]]; then
75 # shellcheck disable=SC1090
79 # We prevent the program from running more than one instance:
80 PIDFILE
=/var
/tmp
/$
(basename "$0" .sh
).pid
82 # Make sure the PID file is removed when we kill the process
83 trap 'rm -f $PIDFILE; exit 1' TERM INT
85 if [[ -r $PIDFILE ]]; then
86 # PIDFILE exists, so I guess there's already an instance running
87 # let's kill it and run again
88 # shellcheck disable=SC2046,SC2086
89 kill -s 15 $
(cat $PIDFILE) > /dev
/null
2>&1
90 # should already be deleted by trap, but just to be sure
95 echo $PID > "$PIDFILE"
97 # Export config to file
99 if [ -r ${RCFILE} ]; then
100 echo "Backing up current '${RCFILE}'...."
101 mv -f ${RCFILE} ${RCFILE}.$
(date +%Y
%m
%d_
%H
%M
)
103 echo "Writing '${RCFILE}'...."
104 sed -n '/^set_defaults() {/,/^} # end set_defaults, do not change this line./p' $0 \
105 |
grep -v set_defaults \
106 |
sed -e 's/^\([^=]*\)=\${\1:-\([^}]*\)}/\1=\2/' \
108 if [ -r ${RCFILE} ]; then
109 echo "Taking no further action."
112 echo "Could not write '${RCFILE}'...!"
117 # we should expand on this function to add a sample note and explain a little bit
118 # how the program works.
120 [ -f $RCFILE ] && RC
=$RCFILE || RC
="none"
123 echo "${BASENAME} configuration:
125 base directory: ${BASEDIR}/
126 notes archive: ${NOTESDIR}/
127 notes database: ${DB}
129 text editor: ${EDITOR}
130 terminal: ${TERMINAL}
134 echo "Now I'll create the needed files and directories."
135 read -r -p "Do you wish to continue? (y/N) " ANSWER
139 cat << __EOL__ > ${DB}
142 "version": "${VERSION}",
143 "dbversion": "${DBVERSION}"
151 echo; echo "All done, you can now write your first note."
154 echo "No changes made. Exiting"
160 # check for notes dir existance and create it in case it doesn't exists
161 if [[ ! -d $NOTESDIR ]]; then
162 # we don't have a directory. FIRST RUN?
165 # check if input is a number, returns false or the number itself
180 echo " $0 [PARAMS] [note ID]..."
182 echo "${BASENAME} parameters are:"
183 echo -e " -h | --help\t\t\t: This help text"
184 echo -e " -p | --plain\t\t\t: Output is in plain text"
185 echo -e "\t\t\t\t (without this option the output is formatted)"
186 echo -e "\t\t\t\t (this option must precede all others)"
187 echo -e " -l | --list\t\t\t: List existing notes"
188 echo -e " -a | --add=[\"<title>\"]\t: Add new note"
189 echo -e " -e | --edit=[<note>]\t\t: Edit note"
190 echo -e " -d | --delete=[<note> | all] : Delete single note or all notes at once"
191 echo -e " -s | --show=[<note>]\t\t: Display note using your favourite PAGER"
192 echo -e " -r | --restore=[<dir>]\t: Restore a previous backup from dir"
193 echo -e " -v | --version\t\t: Print version"
194 echo -e " --userconf\t\t\t: Export User config file"
195 echo -e " --backup [<dest>]\t\t: Backup your data in your destination folder"
197 echo -e "if a non option is passed and is a valid note ID, the note will be displayed."
201 [ $USEGIT ] && GITUSE
="enabled" || GITUSE
="disabled"
203 echo -e "${BASENAME} configuration is:"
205 echo -e "base directory: ${BASEDIR}/"
206 echo -e "notes archive: ${NOTESDIR}/"
207 echo -e "notes database: ${DB}"
208 echo -e "rc file: $RCFILE"
209 echo -e "debug file: /tmp/debug_bash-note.log"
211 echo -e "text editor: ${EDITOR}"
212 echo -e "terminal: ${TERMINAL}"
213 echo -e "jq executable: ${JQ}"
214 echo -e "PAGER: ${PAGER}"
216 echo -e "GIT use: ${GITUSE}"
217 echo -e "GIT remote: ${GITREMOTE}"
218 echo -e "GIT sync delay: ${GITSYNCDELAY}"
221 # this function returns a random 2 words title
225 DICT
=/usr
/share
/dict
/words
228 # total number of non-random words available
229 COUNT
=$
(cat $DICT |
wc -l)
231 # while loop to generate random words
234 RAND
=$
(od -N3 -An -i /dev
/urandom |
awk -v f
=0 -v r
="$COUNT" '{printf "%i\n", f + r * $1 / 16777216}')
235 OUTPUT
+="$(sed `echo $RAND`"q
;d
" $DICT)"
237 [[ $X -eq 1 ]] && OUTPUT
+=" "
243 # check if GITCLIENT has been set or set it to the output of hostname
244 if [ -z "$GITCLIENT" ]; then
245 GITCLIENT
=$
( hostname
)
247 # returns true if the argument provided directory is a git repository
250 if [[ -d $DIR ]]; then
252 if git rev-parse
2>/dev
/null
; then
260 # sync local repository to remote
261 # accepts -f parameter to skip last sync check
264 if [[ $USEGIT && -n $GITREMOTE ]]; then
265 [ $PLAIN == false
] && echo "Syncing notes with git on remote \"$GITREMOTE\""
267 if [[ $FORCE == "-f" ]]; then
268 $JQ --arg n
"$NOWSYNC" '.git["lastpull"] = $n' "$DB" > $TMPDB
271 [ $PLAIN == false
] && $GIT pull ||
$GIT pull
-q
273 # LASTSYNC is the last time we synced to the remote, or 0 if it's the first time.
274 LASTSYNC
=$
($JQ -r '.git["lastpull"] // 0' "$DB")
275 SYNCDIFF
=$
(( ${NOWSYNC} - ${LASTSYNC} ))
276 if (( $SYNCDIFF > $GITSYNCDELAY )); then
277 #more than our delay time has passed. We can sync again.
278 $JQ --arg n
"$NOWSYNC" '.git["lastpull"] = $n' "$DB" > $TMPDB
281 [ $PLAIN == false
] && $GIT pull ||
$GIT pull
-q
283 # Last synced less than $GITSYNCDELAY seconds ago. We shall wait
284 [ $PLAIN == false
] && echo "Last synced less than $GITSYNCDELAY seconds ago. We shall wait"
288 # no git, so we just keep going
293 # add note to git and push it to remote
295 if [[ $USEGIT && -n $GITREMOTE ]]; then
296 [ $PLAIN == false
] && echo "Adding note to remote \"$GITREMOTE\""
299 $GIT commit
-m "$(basename $0) - adding note from ${GITCLIENT}"
300 $GIT push origin master
302 # no git, so we just keep going
307 # edited note added to git and pushed it to remote
309 if [[ $USEGIT && -n $GITREMOTE ]]; then
310 [ $PLAIN == false
] && echo "Editing note on remote \"$GITREMOTE\""
313 $GIT commit
-m "$(basename $0) - ${GITCLIENT} note edited."
314 $GIT push origin master
316 # no git, so we just keep going
321 # add note to git and push it to remote
325 if [[ $USEGIT && -n $GITREMOTE ]]; then
326 [ $PLAIN == false
] && echo "Deleting notes from remote \"$GITREMOTE\""
327 if [ "all" == $NOTE ];then
328 echo "Deleting all notes"
331 $GIT commit
-m "$(basename $0) - ${GITCLIENT} removing all notes."
332 $GIT push origin master
334 echo "Deleting note ID ${NOTE}"
335 local OK
=$
(check_noteID
"$NOTE")
337 $GIT rm notes
/${FILE}
339 $GIT commit
-m "$(basename $0) - ${GITCLIENT} removing note ID ${NOTE}."
340 $GIT push origin master
343 # no git, so we just keep going
348 # check for USEGIT and subsequent variables
349 if [[ $USEGIT && -n $GITREMOTE ]]; then
351 if ! is_git_repo
$BASEDIR; then
352 # initializing git repository
355 echo "adding all files to git"
357 $GIT commit
-m "$(basename $0) - initial commit from ${GITCLIENT}"
358 $GIT remote add origin
$GITREMOTE
359 $GIT push
-u origin master
361 elif [[ $USEGIT && -z $GITREMOTE ]]; then
362 echo "GITREMOTE variable not set. reverting USEGIT to false"
367 # attempt syncing before adding a note
369 # remove eventually existing temp DB file
370 if [[ -f $TMPDB ]]; then
374 RTITLE
=$
(random_title
)
375 [[ -z "$1" ]] && NOTETITLE
="$RTITLE" || NOTETITLE
="$1"
376 echo "adding new note - \"$NOTETITLE\""
377 # shellcheck disable=SC2086
378 LASTID
=$
($JQ '.notes[-1].id // 0 | tonumber' $DB)
379 # [ "" == $LASTID ] && LASTID=0
380 NOTEID
=$
(( LASTID
+ 1 ))
381 # shellcheck disable=SC2086
382 touch ${NOTESDIR}/${NOW}
383 # shellcheck disable=SC2016
384 $JQ --arg i
"$NOTEID" --arg t
"$NOTETITLE" --arg f
"$NOW" '.notes += [{"id": $i, "title": $t, "file": $f}]' "$DB" > $TMPDB
385 # shellcheck disable=SC2086
387 # example for alacritty:
388 # alacritty --class notes --title notes -e /usr/bin/vim ...
389 # shellcheck disable=SC2086,SC2091
390 $
(${TERMINAL} ${TERM_OPTS} ${EDITOR} ${NOTESDIR}/${NOW})
391 # add note to git and push to remote
396 echo "backing up data in $BACKUPDIR"
399 if [ -d $BACKUPDIR ]; then
400 if [ $
(/bin
/ls -A $BACKUPDIR) ]; then
401 echo "$BACKUPDIR is not empty. Cannot continue"
404 echo "$BACKUPDIR is ok. Continuing!"
407 # BACKUPDIR doesn't exists
408 echo "$BACKUPDIR doesn't exists"
409 read -r -p "Do you want me to create it for you? (y/N) " ANSWER
415 echo "No changes made. Exiting"
420 # ok, we have a backup directory
421 if [ -r $RCFILE ]; then
422 BCKUP_COMM
=$
(rsync
-avz --progress ${RCFILE}* ${BASEDIR}/ ${BACKUPDIR})
424 BCKUP_COMM
=$
(rsync
-avz --progress ${BASEDIR}/ ${BACKUPDIR})
427 if [ "$BCKUP_COMM" ]; then
428 echo -e "All files backed up."
429 echo -e "BACKUP directory:\t$BACKUPDIR"
430 tree
$BACKUPDIR |
$PAGER
431 echo; echo "BACKUP COMPLETED"
437 echo "restoring backup from $BACKUPDIR"
438 echo "This will overwrite all your notes and configurations with the backup."
439 read -r -p "Do you want to continue? (y/N) " ANSWER
443 BACKUPRC
=$
(basename $RCFILE)
444 if [ -r ${BACKUPDIR}/${BACKUPRC} ]; then
445 if [ -r ${RCFILE} ]; then
446 echo "Backing up current '${RCFILE}'...."
447 mv -f ${RCFILE} ${RCFILE}.$
(date +%Y
%m
%d_
%H
%M
)
449 cp --verbose ${BACKUPDIR}/${BACKUPRC} $RCFILE
451 # restoring notes directory
452 if [ -d $BACKUPDIR/notes
]; then
453 if [ $
(/bin
/ls -A $NOTESDIR) ]; then
454 rm --verbose $NOTESDIR/*
456 cp -r --verbose $BACKUPDIR/notes
$BASEDIR
459 BACKUPDB
=$
(basename $DB)
460 if [ -f ${BACKUPDIR}/${BACKUPDB} ]; then
461 if [ -r ${DB} ]; then
462 echo "Backing up current '${DB}'...."
463 mv -f ${DB} ${DB}.$
(date +%Y
%m
%d_
%H
%M
)
465 cp --verbose ${BACKUPDIR}/${BACKUPDB} $DB
467 # restoring git repo subdirectory
468 if [ -d $BACKUPDIR/.git
]; then
469 if [ /bin
/ls -A ${BASEDIR}/.git
]; then
470 rm -rf ${BASEDIR}/.git
472 cp -r --verbose ${BACKUPDIR}/.git
${BASEDIR}/
476 echo "No changes made. Exiting"
484 # shellcheck disable=SC2155
485 local OK
=$
(check_noteID
"$NOTE")
487 echo "invalid note \"$NOTE\""
488 echo "Use the note ID that you can fetch after listing your notes"
492 # shellcheck disable=SC2016,SC2086
493 TITLE
=$
($JQ --arg i
$OK '.notes[] | select(.id == $i) | .title' $DB)
494 # shellcheck disable=SC2016,SC2086
495 FILE
=$
($JQ -r --arg i
$OK '.notes[] | select(.id == $i) | .file' $DB)
496 if [ "$TITLE" ]; then
497 echo "editing note $TITLE"
498 # shellcheck disable=SC2086,SC2091
499 $
(${TERMINAL} ${TERM_OPTS} ${EDITOR} ${NOTESDIR}/${FILE})
502 echo "note not found"
507 # attempt syncing before listing all notes
509 # [ $PLAIN == true ] && echo "output is plain text" || echo "output is colored"
510 if [[ $
(ls -A "$NOTESDIR") ]]; then
511 if [ $PLAIN == false
]; then
512 echo "listing all notes"
515 [ $PLAIN == false
] && echo "[ID] [TITLE] [CREATED]"
516 for i
in "${NOTESDIR}"/*; do
517 # shellcheck disable=SC2155
518 local fname
=$
(basename $i)
519 DATE
=$
(date -d @
${fname} +"%d/%m/%Y %R %z%Z")
520 # shellcheck disable=SC2016,SC2086
521 TITLE
=$
($JQ -r --arg z $
(basename $i) '.notes[] | select(.file == $z) | .title' $DB)
522 # shellcheck disable=SC2016,SC2086
523 ID
=$
($JQ -r --arg z $
(basename $i) '.notes[] | select(.file == $z) | .id' $DB)
524 [ $PLAIN == false
] && echo "[${ID}] ${TITLE} ${DATE}" || echo "${ID} - ${TITLE} - ${DATE}"
527 echo "no notes yet. You can add your first one with: ${BASENAME} -a \"your note title\""
531 # remove eventually existing temp DB file
532 if [[ -f $TMPDB ]]; then
537 if [ "all" == "$NOTE" ]; then
538 echo "You're going to delete all notes."
539 read -r -p "Do you wish to continue? (y/N) " ANSWER
542 # shellcheck disable=SC2086
543 $JQ 'del(.notes[])' $DB > $TMPDB
544 # shellcheck disable=SC2086
546 # shellcheck disable=SC2086
549 echo "Deleted all notes"
552 echo "Aborting, no notes were deleted."
557 # shellcheck disable=SC2155
558 local OK
=$
(check_noteID
"$NOTE")
560 echo "invalid note \"$NOTE\""
561 echo "Use the note ID that you can fetch after listing your notes"
566 # shellcheck disable=SC2016,SC2086
567 TITLE
=$
($JQ --arg i
$OK '.notes[] | select(.id == $i) | .title' $DB)
568 # shellcheck disable=SC2016,SC2086
569 FILE
=$
($JQ -r --arg i
$OK '.notes[] | select(.id == $i) | .file' $DB)
570 if [ "$TITLE" ]; then
571 # shellcheck disable=SC2016,SC2086
572 $JQ -r --arg i
$OK 'del(.notes[] | select(.id == $i))' $DB > $TMPDB
573 # shellcheck disable=SC2086
577 echo "Deleted note $TITLE"
581 echo "note not found"
590 # shellcheck disable=SC2155
591 local OK
=$
(check_noteID
"$NOTE")
593 echo "invalid note \"$NOTE\""
594 echo "Use the note ID that you can fetch after listing your notes"
598 FILE
=$
($JQ -r --arg i
$OK '.notes[] | select(.id == $i) | .file' $DB)
601 $PAGER ${NOTESDIR}/${FILE}
604 # shellcheck disable=SC2006
605 GOPT
=$
(getopt
-o hvplr
::a
::e
::d
::s
:: --long help,version
,list
,plain
,userconf
,showconf
,sync
::,restore
::,backup
::,add
::,edit
::,delete
::,show
:: -n 'bash-notes' -- "$@")
607 # shellcheck disable=SC2181
608 if [ $?
!= 0 ] ; then helptext
>&2 ; exit 1 ; fi
610 # Note the quotes around `$GOPT': they are essential!
621 echo $BASENAME v
${VERSION}
635 read -r -p "Title: " TITLE
648 read -r -p "Note ID: " NOTE
661 read -r -p "Note ID: " NOTE
674 read -r -p "Note ID: " NOTE
687 read -r -p "Backup Dir: " RDIR
715 # shellcheck disable=SC2317
716 echo "config exported to \"$RCFILE\""
717 # shellcheck disable=SC2317
727 read -r -p "Backup Dir: " BDIR
748 if [ $
(check_noteID
$arg) ]; then