Skip to content

Instantly share code, notes, and snippets.

@webstrand
Created November 9, 2024 21:46
Show Gist options
  • Save webstrand/7cee27d90b61a9c8229c30bd1fc40d6f to your computer and use it in GitHub Desktop.
Save webstrand/7cee27d90b61a9c8229c30bd1fc40d6f to your computer and use it in GitHub Desktop.
A command to create or update the named (default: temporary-vault) Obsidian Vault and open it in Obsidian.
#!/bin/bash
set -euo pipefail
shopt -s lastpipe
name="temporary-vault"
already_set_path=
path="$(pwd)"
_usage() {
local status=${1:-0}
[[ $status != 0 ]] && exec 1>&2
cat <<EOF
Usage: $0 [-n|--name <string>] [--] [<path>]
Creates or updates the named Obsidian Vault to point at <path>
and then opens that vault in Obsidian.
Options:
-n, --name <string> Name of vault to create or replace (default: $name)
-h, --help Show this help message
Arguments:
path Path to the directory to use as the root of the vault
(default: $path)
EOF
exit $status
}
ignore_opts=
while [[ "$#" -gt 0 ]]; do
case "$ignore_opts$1" in
'--name'|'-n')
if [[ ${2:-} =~ ^(--|$) ]]; then
echo "Error: $1 requires a non-empty string argument" >&2
exit 1
fi
name="$2"
shift 1
;;
'--help'|'-h') _usage 0 ;;
'--') ignore_opts=x ;;
--*) echo "Error: unknown option '$1'" >&2; _usage 1 ;;
*)
if [[ -n $already_set_path ]]; then
echo "Error: excess positional argument '$1'" >&2
exit 1
fi
already_set_path=true
path=$(realpath -s "$1")
;;
esac
shift 1
done
config_dir="${XDG_config_file_HOME:-$HOME/.config}/obsidian"
config_file="$config_dir/obsidian.json"
# Verify that we can both read and write to the config file
if [[ ! -r $config_file || ! -w $config_file ]]; then
echo "Error: Unable to access '$config_file' for modification"
exit 1
fi
# Verify that we can make the temporary file
if [[ ! -w $config_dir ]]; then
echo "Error: Unable to write temporary file to '$config_dir'"
exit 1
fi
# Temporary file to contain jq output
tmpfile=$(mktemp "$config_file".XXXXXXXX)
trap "rm -f ${tmpfile@Q}" EXIT
# Preserve the original permissions and ACLs
cp --one-file-system \
--dereference \
--update=all \
--preserve=all \
--attributes-only \
"$config_file" "$tmpfile"
< "$config_file" \
jq --arg name "$name" \
--arg path "$path" \
'.vaults[$name] = { path: $path, ts: 0 }' \
> "$tmpfile"
# Try very hard to avoid accidentally truncating or otherwise
# corrupting obsidian's config file.
orig_size=$(stat --printf="%s" "$config_file")
modf_size=$(stat --printf="%s" "$tmpfile")
if (( $orig_size - $modf_size > ${#path} )); then
echo "Error: suspicious decrease in filesize, aborting due to potential corruption"
exit 1
fi
mv "$tmpfile" "$config_file"
exec obsidian "obsidian://open?vault=$name"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment