Tired of having to manually enter the git commands to get latest again and again, I added this script to my .zshrc file in VSCode to handle the process for me.
gitLatest()
{
git status
echo "This action will overwrite any uncommitted changes. Are you sure? (y/n): "
read -e overwrite
if [[ "$overwrite" == "y" ]] ; then
git checkout main
git fetch
git reset --hard origin/main
fi
}
When I run the script, the directions are displayed and I enter "y" at the prompt. The "y" is re-printed and the script terminates.
I've tried reformatting the if statement portion a number of ways according to blog posts and SO posts that seemed tangibly related to get the logic to trigger but no action so far gets into the if statement.
The documentation for read
is tricky to find; it's in man zshbuiltins
. It has this note:
-e
-E
The input read is printed (echoed) to the standard output. If the-e
flag is used, no input is assigned to the parameters.
So nothing is being assigned to the overwrite
variable. -E
should work:
> read -e var
qwerty
qwerty
> typeset -p var
typeset: no such variable: var
> read -E var
asdf
asdf
> typeset -p var
typeset var=asdf
> if [[ $var == asdf ]] print YES
YES
The -q
option for read
supports another way to build confirmation prompts:
-q
Read only one character from the terminal and set name to ‘y’ if this character was ‘y’ or ‘Y’ and to ‘n’ otherwise. With this flag set the return status is zero only if the character was ‘y’ or ‘Y’. This option may be used with a timeout (see-t
); if the read times out, or encounters end of file, status 2 is returned. ...
Now there's no need to hit return:
> if read -q 'var?overwrite (y/n)?'; then
then> print;print "as you wish"
then> fi
overwrite (y/n)?y
as you wish