62fbd30ac19c7667e6aa869dd97735d05cbc44c6
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}
57 } # end set_defaults, do not change this line.
61 # Do not edit below this point
62 RCFILE
=${RCFILE:-~/.config/bash-notes.rc}
65 if [ ! -x "$JQ" ]; then
66 echo "jq not found in your PATH"
67 echo "install jq to continue"
71 # IMPORT USER DEFINED OPTIONS IF ANY
72 if [[ -f $RCFILE ]]; then
73 # shellcheck disable=SC1090
77 # We prevent the program from running more than one instance:
78 PIDFILE
=/var
/tmp
/$
(basename "$0" .sh
).pid
80 # Make sure the PID file is removed when we kill the process
81 trap 'rm -f $PIDFILE; exit 1' TERM INT
83 if [[ -r $PIDFILE ]]; then
84 # PIDFILE exists, so I guess there's already an instance running
85 # let's kill it and run again
86 # shellcheck disable=SC2046,SC2086
87 kill -s 15 $
(cat $PIDFILE) > /dev
/null
2>&1
88 # should already be deleted by trap, but just to be sure
93 echo $PID > "$PIDFILE"
95 # Export config to file
97 if [ -r ${RCFILE} ]; then
98 echo "Backing up current '${RCFILE}'...."
99 mv -f ${RCFILE} ${RCFILE}.$
(date +%Y
%m
%d_
%H
%M
)
101 echo "Writing '${RCFILE}'...."
102 sed -n '/^set_defaults() {/,/^} # end set_defaults, do not change this line./p' $0 \
103 |
grep -v set_defaults \
104 |
sed -e 's/^\([^=]*\)=\${\1:-\([^}]*\)}/\1=\2/' \
106 if [ -r ${RCFILE} ]; then
107 echo "Taking no further action."
110 echo "Could not write '${RCFILE}'...!"
115 # we should expand on this function to add a sample note and explain a little bit
116 # how the program works.
118 [ -f $RCFILE ] && RC
=$RCFILE || RC
="none"
121 echo "${BASENAME} configuration:
123 base directory: ${BASEDIR}/
124 notes archive: ${NOTESDIR}/
125 notes database: ${DB}
127 text editor: ${EDITOR}
128 terminal: ${TERMINAL}
132 echo "Now I'll create the needed files and directories."
133 read -r -p "Do you wish to continue? (y/N) " ANSWER
137 cat << __EOL__ > ${DB}
140 "version": "${VERSION}",
141 "dbversion": "${DBVERSION}"
149 echo; echo "All done, you can now write your first note."
152 echo "No changes made. Exiting"
158 # check for notes dir existance and create it in case it doesn't exists
159 if [[ ! -d $NOTESDIR ]]; then
160 # we don't have a directory. FIRST RUN?
163 # check if input is a number, returns false or the number itself
178 echo " $0 [PARAMS] [note ID]..."
180 echo "${BASENAME} parameters are:"
181 echo -e " -h | --help\t\t\t: This help text"
182 echo -e " -p | --plain\t\t\t: Output is in plain text"
183 echo -e "\t\t\t\t (without this option the output is formatted)"
184 echo -e "\t\t\t\t (this option must precede all others)"
185 echo -e " -l | --list\t\t\t: List existing notes"
186 echo -e " -a | --add=[\"<title>\"]\t: Add new note"
187 echo -e " -e | --edit=[<note>]\t\t: Edit note"
188 echo -e " -d | --delete=[<note> | all] : Delete single note or all notes at once"
189 echo -e " -s | --show=[<note>]\t\t: Display note using your favourite PAGER"
190 echo -e " -r | --restore=[<dir>]\t: Restore a previous backup from dir"
191 echo -e " -v | --version\t\t: Print version"
192 echo -e " --userconf\t\t\t: Export User config file"
193 echo -e " --backup [<dest>]\t\t: Backup your data in your destination folder"
195 echo -e "if a non option is passed and is a valid note ID, the note will be displayed."
200 ${BASENAME} configuration is:
202 base directory: ${BASEDIR}/
203 notes archive: ${NOTESDIR}/
204 notes database: ${DB}
206 debug file: /tmp/debug_bash-note.log
208 text editor: ${EDITOR}
209 terminal: ${TERMINAL}
216 # this function returns a random 2 words title
220 DICT
=/usr
/share
/dict
/words
223 # total number of non-random words available
224 COUNT
=$
(cat $DICT |
wc -l)
226 # while loop to generate random words
229 RAND
=$
(od -N3 -An -i /dev
/urandom |
awk -v f
=0 -v r
="$COUNT" '{printf "%i\n", f + r * $1 / 16777216}')
230 OUTPUT
+="$(sed `echo $RAND`"q
;d
" $DICT)"
232 [[ $X -eq 1 ]] && OUTPUT
+=" "
238 # returns true if the argument provided directory is a git repository
241 if [[ -d $DIR ]]; then
243 if git rev-parse
2>/dev
/null
; then
251 # sync local repository to remote
254 # LASTSYNC is the last time we synced to the remote, or 0 if it's the first time.
255 LASTSYNC
=$
($JQ -r '.git["lastpull"] // 0' "$DB")
256 [ $PLAIN == false
] && echo "Syncing notes with git on remote \"$GITREMOTE\""
257 SYNCDIFF
=$
(( ${NOWSYNC} - ${LASTSYNC} ))
258 if (( $SYNCDIFF > $GITSYNCDELAY )); then
259 #more than our delay time has passed. We can sync again.
260 $JQ --arg n
"$NOWSYNC" '.git["lastpull"] = $n' "$DB" > $TMPDB
265 # Last synced less than $GITSYNCDELAY seconds ago. We shall wait
266 [ $PLAIN == false
] && echo "Last synced less than $GITSYNCDELAY seconds ago. We shall wait"
270 # check for USEGIT and subsequent variables
271 if [[ $USEGIT && -n $GITREMOTE ]]; then
273 if ! is_git_repo
$BASEDIR; then
274 # initializing git repository
277 echo "adding all files to git"
279 $GIT commit
-m "$(basename $0) - initial commit"
280 $GIT remote add origin
$GITREMOTE
281 $GIT push
-u origin master
283 elif [[ $USEGIT && -z $GITREMOTE ]]; then
284 echo "GITREMOTE variable not set. reverting USEGIT to false"
289 # remove eventually existing temp DB file
290 if [[ -f $TMPDB ]]; then
294 RTITLE
=$
(random_title
)
295 [[ -z "$1" ]] && NOTETITLE
="$RTITLE" || NOTETITLE
="$1"
296 echo "adding new note - \"$NOTETITLE\""
297 # shellcheck disable=SC2086
298 LASTID
=$
($JQ '.notes[-1].id // 0 | tonumber' $DB)
299 # [ "" == $LASTID ] && LASTID=0
300 NOTEID
=$
(( LASTID
+ 1 ))
301 # shellcheck disable=SC2086
302 touch ${NOTESDIR}/${NOW}
303 # shellcheck disable=SC2016
304 $JQ --arg i
"$NOTEID" --arg t
"$NOTETITLE" --arg f
"$NOW" '.notes += [{"id": $i, "title": $t, "file": $f}]' "$DB" > $TMPDB
305 # shellcheck disable=SC2086
307 # example for alacritty:
308 # alacritty --class notes --title notes -e /usr/bin/vim ...
309 # shellcheck disable=SC2086,SC2091
310 $
(${TERMINAL} ${TERM_OPTS} ${EDITOR} ${NOTESDIR}/${NOW})
314 echo "backing up data in $BACKUPDIR"
317 if [ -d $BACKUPDIR ]; then
318 if [ $
(/bin
/ls -A $BACKUPDIR) ]; then
319 echo "$BACKUPDIR is not empty. Cannot continue"
322 echo "$BACKUPDIR is ok. Continuing!"
325 # BACKUPDIR doesn't exists
326 echo "$BACKUPDIR doesn't exists"
327 read -r -p "Do you want me to create it for you? (y/N) " ANSWER
333 echo "No changes made. Exiting"
338 # ok, we have a backup directory
339 if [ -r $RCFILE ]; then
340 BCKUP_COMM
=$
(rsync
-avz --progress ${RCFILE}* ${BASEDIR}/ ${BACKUPDIR})
342 BCKUP_COMM
=$
(rsync
-avz --progress ${BASEDIR}/ ${BACKUPDIR})
345 if [ "$BCKUP_COMM" ]; then
346 echo -e "All files backed up."
347 echo -e "BACKUP directory:\t$BACKUPDIR"
348 tree
$BACKUPDIR |
$PAGER
349 echo; echo "BACKUP COMPLETED"
355 echo "restoring backup from $BACKUPDIR"
356 echo "This will overwrite all your notes and configurations with the backup."
357 read -r -p "Do you want to continue? (y/N) " ANSWER
361 BACKUPRC
=$
(basename $RCFILE)
362 if [ -r ${BACKUPDIR}/${BACKUPRC} ]; then
363 if [ -r ${RCFILE} ]; then
364 echo "Backing up current '${RCFILE}'...."
365 mv -f ${RCFILE} ${RCFILE}.$
(date +%Y
%m
%d_
%H
%M
)
367 cp --verbose ${BACKUPDIR}/${BACKUPRC} $RCFILE
369 # restoring notes directory
370 if [ -d $BACKUPDIR/notes
]; then
371 if [ $
(/bin
/ls -A $NOTESDIR) ]; then
372 rm --verbose $NOTESDIR/*
374 cp -r --verbose $BACKUPDIR/notes
$BASEDIR
377 BACKUPDB
=$
(basename $DB)
378 if [ -f ${BACKUPDIR}/${BACKUPDB} ]; then
379 if [ -r ${DB} ]; then
380 echo "Backing up current '${DB}'...."
381 mv -f ${DB} ${DB}.$
(date +%Y
%m
%d_
%H
%M
)
383 cp --verbose ${BACKUPDIR}/${BACKUPDB} $DB
385 # restoring git repo subdirectory
386 if [ -d $BACKUPDIR/.git
]; then
387 if [ /bin
/ls -A ${BASEDIR}/.git
]; then
388 rm -rf ${BASEDIR}/.git
390 cp -r --verbose ${BACKUPDIR}/.git
${BASEDIR}/
394 echo "No changes made. Exiting"
402 # shellcheck disable=SC2155
403 local OK
=$
(check_noteID
"$NOTE")
405 echo "invalid note \"$NOTE\""
406 echo "Use the note ID that you can fetch after listing your notes"
410 # shellcheck disable=SC2016,SC2086
411 TITLE
=$
($JQ --arg i
$OK '.notes[] | select(.id == $i) | .title' $DB)
412 # shellcheck disable=SC2016,SC2086
413 FILE
=$
($JQ -r --arg i
$OK '.notes[] | select(.id == $i) | .file' $DB)
414 if [ "$TITLE" ]; then
415 echo "editing note $TITLE"
416 # shellcheck disable=SC2086,SC2091
417 $
(${TERMINAL} ${TERM_OPTS} ${EDITOR} ${NOTESDIR}/${FILE})
419 echo "note not found"
424 # attempt syncing before listing all notes
426 # [ $PLAIN == true ] && echo "output is plain text" || echo "output is colored"
427 if [[ $
(ls -A "$NOTESDIR") ]]; then
428 if [ $PLAIN == false
]; then
429 echo "listing all notes"
432 [ $PLAIN == false
] && echo "[ID] [TITLE] [CREATED]"
433 for i
in "${NOTESDIR}"/*; do
434 # shellcheck disable=SC2155
435 local fname
=$
(basename $i)
436 DATE
=$
(date -d @
${fname} +"%d/%m/%Y %R %z%Z")
437 # shellcheck disable=SC2016,SC2086
438 TITLE
=$
($JQ -r --arg z $
(basename $i) '.notes[] | select(.file == $z) | .title' $DB)
439 # shellcheck disable=SC2016,SC2086
440 ID
=$
($JQ -r --arg z $
(basename $i) '.notes[] | select(.file == $z) | .id' $DB)
441 [ $PLAIN == false
] && echo "[${ID}] ${TITLE} ${DATE}" || echo "${ID} - ${TITLE} - ${DATE}"
444 echo "no notes yet. You can add your first one with: ${BASENAME} -a \"your note title\""
448 # remove eventually existing temp DB file
449 if [[ -f $TMPDB ]]; then
454 if [ "all" == "$NOTE" ]; then
455 echo "You're going to delete all notes."
456 read -r -p "Do you wish to continue? (y/N) " ANSWER
459 # shellcheck disable=SC2086
460 $JQ 'del(.notes[])' $DB > $TMPDB
461 # shellcheck disable=SC2086
463 # shellcheck disable=SC2086
465 echo "Deleted all notes"
468 echo "Aborting, no notes were deleted."
473 # shellcheck disable=SC2155
474 local OK
=$
(check_noteID
"$NOTE")
476 echo "invalid note \"$NOTE\""
477 echo "Use the note ID that you can fetch after listing your notes"
482 # shellcheck disable=SC2016,SC2086
483 TITLE
=$
($JQ --arg i
$OK '.notes[] | select(.id == $i) | .title' $DB)
484 # shellcheck disable=SC2016,SC2086
485 FILE
=$
($JQ -r --arg i
$OK '.notes[] | select(.id == $i) | .file' $DB)
486 if [ "$TITLE" ]; then
487 # shellcheck disable=SC2016,SC2086
488 $JQ -r --arg i
$OK 'del(.notes[] | select(.id == $i))' $DB > $TMPDB
489 # shellcheck disable=SC2086
492 echo "Deleted note $TITLE"
496 echo "note not found"
505 # shellcheck disable=SC2155
506 local OK
=$
(check_noteID
"$NOTE")
508 echo "invalid note \"$NOTE\""
509 echo "Use the note ID that you can fetch after listing your notes"
513 FILE
=$
($JQ -r --arg i
$OK '.notes[] | select(.id == $i) | .file' $DB)
516 $PAGER ${NOTESDIR}/${FILE}
519 # shellcheck disable=SC2006
520 GOPT
=$
(getopt
-o hvplr
::a
::e
::d
::s
:: --long help,version
,list
,plain
,userconf
,sync
,restore
::,backup
::,add
::,edit
::,delete
::,show
:: -n 'bash-notes' -- "$@")
522 # shellcheck disable=SC2181
523 if [ $?
!= 0 ] ; then helptext
>&2 ; exit 1 ; fi
525 # Note the quotes around `$GOPT': they are essential!
536 echo $BASENAME v
${VERSION}
550 read -r -p "Title: " TITLE
563 read -r -p "Note ID: " NOTE
576 read -r -p "Note ID: " NOTE
589 read -r -p "Note ID: " NOTE
602 read -r -p "Backup Dir: " RDIR
618 # shellcheck disable=SC2317
619 echo "config exported to \"$RCFILE\""
620 # shellcheck disable=SC2317
626 read -r -p "Backup Dir: " BDIR
647 if [ $
(check_noteID
$arg) ]; then