refactor to use POSIX sh (linted with `shellcheck`)

This commit is contained in:
Joel Beckmeyer 2021-11-30 08:58:37 -05:00
parent fd386dbeda
commit 29f6b55fff
2 changed files with 16 additions and 16 deletions

View File

@ -1,5 +1,5 @@
# doasedit # doasedit
a Bash script replacement for sudoedit using doas. a POSIX shell replacement for sudoedit using doas.
[Inspired by this Reddit comment.](https://www.reddit.com/r/linux/comments/l6y7nv/is_doas_a_good_alternative_to_sudo/gl4hs42?utm_source=share&utm_medium=web2x&context=3) [Inspired by this Reddit comment.](https://www.reddit.com/r/linux/comments/l6y7nv/is_doas_a_good_alternative_to_sudo/gl4hs42?utm_source=share&utm_medium=web2x&context=3)
## USE AT YOUR OWN RISK! THIS SCRIPT IS VERY ALPHA. ## USE AT YOUR OWN RISK! THIS SCRIPT IS VERY ALPHA.

View File

@ -1,44 +1,44 @@
#!/bin/bash #!/bin/sh
if [ ! -z "${2}" ]; then if [ -n "${2}" ]; then
echo "Expected only one argument" echo "Expected only one argument"
exit 1 exit 1
elif [ -z "${1}" ]; then elif [ -z "${1}" ]; then
echo "No file path provided" echo "No file path provided"
exit 1 exit 1
elif [ "$EUID" -eq 0 ]; then elif [ "$(id -u)" -eq 0 ]; then
echo "Cannot be run as root" echo "Cannot be run as root"
exit 1 exit 1
fi fi
set -Eeuo pipefail set -eu
tempdir="$(mktemp -d)" tempdir="$(mktemp -d)"
trap "rm -rf $tempdir" EXIT trap 'rm -rf $tempdir' EXIT
srcfile="$(doas realpath $1)" srcfile="$(doas realpath "$1")"
if doas [ -f "$srcfile" ]; then if doas [ -f "$srcfile" ]; then
doas cp -a $srcfile $tempdir/file doas cp -a "$srcfile" "$tempdir"/file
doas cp -a $tempdir/file $tempdir/edit doas cp -a "$tempdir"/file "$tempdir"/edit
# make sure that the file is editable by user # make sure that the file is editable by user
doas chown $USER:$USER $tempdir/edit doas chown "$USER":"$USER" "$tempdir"/edit
chmod 600 $tempdir/edit chmod 600 "$tempdir"/edit
else else
# create file with "regular" system permissions (root:root 644) # create file with "regular" system permissions (root:root 644)
touch $tempdir/file touch "$tempdir"/file
doas chown root:root $tempdir/file doas chown root:root "$tempdir"/file
fi fi
$EDITOR $tempdir/edit $EDITOR "$tempdir"/edit
cat $tempdir/edit | doas tee $tempdir/file 1>/dev/null doas tee "$tempdir"/file 1>/dev/null < "$tempdir"/edit
if doas cmp -s "$tempdir/file" "$srcfile"; then if doas cmp -s "$tempdir/file" "$srcfile"; then
echo "Skipping write; no changes." echo "Skipping write; no changes."
exit 0 exit 0
else else
doas mv -f $tempdir/file $srcfile doas mv -f "$tempdir"/file "$srcfile"
exit 0 exit 0
fi fi