Skip to content

Instantly share code, notes, and snippets.

@fnord0
Last active December 9, 2021 21:36
Show Gist options
  • Save fnord0/b225617f6899a17d7f498170e5ffc0c2 to your computer and use it in GitHub Desktop.
Save fnord0/b225617f6899a17d7f498170e5ffc0c2 to your computer and use it in GitHub Desktop.
MSYS2 on Windows 10 x64 - including ZSH, oh-my-zsh, powerlevel10k theme, gpg and pass

MSYS2 on Windows 10 x64

https://dev.to/shrihankp/make-your-terminal-look-swag-with-msys2-and-zsh-32b7 https://github.com/romkatv/powerlevel10k#manual-font-installation

choco install -y cmder msys2

Download these four TTF files:

Open Windows Explorer to the location of the TTF downloads, RIGHT-CLICK on each file and click "Install". This will make MesloLGS NF font available to all applications on your system.

Open Cmder Open Cmder/ConEmu Settings by pressing Windows Key+ALT+P Go to Startup > Tasks Create a new task by clicking + Configure the new task as follows:

  • Task Name: MSYS2::MSYS2 shell

  • Task Parameters: /icon "C:\tools\msys64\msys2.ico"

  • Task Commands (this will be modified later on, once ZSH is added)

    set CHERE_INVOKING=1 & set MSYSTEM=MINGW64 & set MSYS2_PATH_TYPE=inherit & set "PATH=C:\tools\msys64\usr\bin;C:\tools\msys64\mingw64\bin;C:\tools\msys64\mingw32\bin;%PATH%" & %ConEmuBaseDirShort%\conemu-msys2-64.exe -new_console:p C:\tools\msys64\usr\bin\bash.exe --login -i -new_console:C:"C:\tools\msys64\msys2.ico"

    Task Commands breakdown of each command:

  • CHERE_INVOKING=1 tells Bash to not cd into the HOME directory always.

  • MSYSTEM=MINGW64 uses Mingw as the MSYS System instead of the Default MSYS, which is slower.

  • MSYS2_PATH_TYPE=inherit if unset MSYS uses a minimal PATH environment that contains only MSYS binaries and a couple select Windows system paths, and is a required mode for MSYSTEM=MSYS shell only. For MINGW shells it's recommended to use inherit -- I've been using MSYS2_PATH_TYPE=inherit without issues for years.

  • PATH=C:\tools\msys64\usr\bin;C:\tools\msys64\mingw64\bin;C:\tools\msys64\mingw32\bin;%PATH% updates the PATH variable to add msys64\usr\bin also msys64\mingw64\bin and msys64\mingw32\bin to use Windows-native binaries, *.exe to serve the purpose of basic Unix commands, like clear , ls , rm , and even utilities like curl. Coming to the PATH, we’re also setting the path to the Native Windows %PATH% variable. This helps to use the already-installed utilities like node, kubectl, docker, npm, etc.

  • conemu-msys2-64.exe , is a helper tool to create the symbiont of POSIX enabled pty and WinAPI full-featured terminal

  • -new_console:p, starts a new Cmder/ConEmu Console Session

    • C:\tools\msys64\usr\bin\bash.exe --login -i runs bash as a login shell (--login) and interactive (-i)
  • -new_console:C:"C:\tools\msys64\msys2.ico" we specify an icon used in the tab

Still within ConEmu Settings go to General > Fonts

Change the Main console font and Alternative font to MesloLGS NF. Change the font size to something larger, personally I use Size: 18.

image-20211208164315921

Optional: Head over to the Features > Colors tab and change the Schemes option to . You can select whatever you like. If you didn’t like any of these, then head over to this page and follow the instructions to install a theme you like. And wherever it says, ConfigPath, it means the path written near the Storage section above all the settings. Mine is C:\tools\Cmder\vendor\conemu-maximus5\ConEmu.xml. I personally prefer , provided with Cmder already.

Launch our MSYS2::MSYS2 shell

image-20211208171013709

Cmder + MSYS2

Run the following commands to update the system

pacman -Syu
pacman -S zsh man vim nano tar openssh rsync make zip unzip
pacman -S mingw64/mingw-w64-x86_64-jq

Note about sudo: MSYS2 doesn't provide it. See this question or imachug/win-sudo.

Git for Windows

If you had Git for Windows installed previously, uninstall it or just remove C:\Program Files\Git\..., or wherever you installed Git, from $PATH

I have Git for Windows which works through an add-on to Cmder itself. When running in the MSYS2 environment on Cmder I found that git was not accessible to me, which is good in this case.

user@host MINGW64 /c/Users/username % git --version
bash: command not found: git
user@host MINGW64 /c/Users/username % which git
git not found

Edit /etc/pacman.conf and just before [mingw32] , add the git-for-windows and git-for-windows-mingw32 packages repository (this is how the whole bottom of my /etc/pacman.conf looks for reference)

# The testing repositories are disabled by default. To enable, uncomment the
# repo name header and Include lines. You can add preferred servers immediately
# after the header, and they will be used before the default mirrors.

[git-for-windows]
Server = https://wingit.blob.core.windows.net/x86-64

[git-for-windows-mingw32]
Server = https://wingit.blob.core.windows.net/i686

[mingw32]
Include = /etc/pacman.d/mirrorlist.mingw

[mingw64]
Include = /etc/pacman.d/mirrorlist.mingw

[ucrt64]
Include = /etc/pacman.d/mirrorlist.mingw

[clang64]
Include = /etc/pacman.d/mirrorlist.mingw

[msys]
Include = /etc/pacman.d/mirrorlist.msys

# An example of a custom package repository.  See the pacman manpage for
# tips on creating your own repositories.
#[custom]
#SigLevel = Optional TrustAll
#Server = file:///home/custompkgs

Authorize a signing key:

curl -L https://raw.githubusercontent.com/git-for-windows/build-extra/HEAD/git-for-windows-keyring/git-for-windows.gpg |
pacman-key --add - &&
pacman-key --lsign-key E8325679DFFF09668AD8D7B67115A57376871B1C &&
pacman-key --lsign-key 3B6D86A1BA7701CD0F23AED888138B9E1A9F3986

Then, update/synchronise the repository with the following commands:

pacman -Syyuu
  • This updates msys2-runtime and therefore will ask you to close the window (not just exit the pacman process). Don't panic, simply close all currently open MSYS2 shells and MSYS2 programs. Double-check Task Manager and kill pacman.exe if it's still running after the window is closed, because it can linger. Once all are closed, start a new MSYS2::MSYS2 shell again.

Then synchronize again (updating the non-core part of the packages):

pacman -Syuu
pacman -Syuu

After that, install git and necessary things:

pacman -S git git-extras
pacman -S mingw-w64-x86_64-git-credential-manager mingw-w64-x86_64-git-lfs mingw-w64-x86_64-git-doc-man mingw-w64-x86_64-git-doc-html

Check that everything works by doing git --version and it should output something like git version 2.34.1 (or newer).

Output for git --version.

Of note, I did get 2 errors that had to do with mingw-w64-x86_64-git-doc-man and mingw-w64-x86_64-git-doc-html. I even went so far as to run the install command twice, but got the same exact errors that looks like this

cannot stat '/mingw64/share/git/compat-bash.exe': No such file or directory
	error: command (/usr/bin/bash /usr/bin/bash -c . /tmp/alpm_6eC1Fr/.INSTALL; post_upgrade 2.34.1.1.2ca94ab318-1 2.34.1.1.2ca94ab318-1 ) failed to execute correctly
cp: cannot stat '/mingw64/share/git/compat-bash.exe': No such file or directory
	error: command (/usr/bin/bash /usr/bin/bash -c . /tmp/alpm_ZMdB3Y/.INSTALL; post_upgrade 2.34.1.1.2ca94ab318-1 2.34.1.1.2ca94ab318-1 ) failed to execute correctly

So far I've noticed no issues, they both were documentation packages, so I am not too worried.

Installing ZSH + OH-MY-ZSH

To install ZSH

pacman -S zsh

We're going to update the Cmder MSYS2::MSYS2 shell Task by adding -c "exec zsh"

  • In Cmder
  • Open Cmder/ConEmu Settings by pressing Windows Key+ALT+P
  • Go to Startup > Tasks
  • Select MSYS2::MSYS2 shell
  • Change the Task Commands to the following:
set CHERE_INVOKING=1 & set MSYSTEM=MINGW64 & set MSYS2_PATH_TYPE=inherit & set "PATH=C:\tools\msys64\usr\bin;C:\tools\msys64\mingw64\bin;C:\tools\msys64\mingw32\bin;%PATH%" & %ConEmuBaseDirShort%\conemu-msys2-64.exe -new_console:p C:\tools\msys64\usr\bin\bash.exe --login -ic "exec zsh" -new_console:C:"C:\tools\msys64\msys2.ico"

Click Save settings button Now, exit Cmder and open it again, you will get zsh shell!

Go through the prompts to get to a command-line (quit)

Install OH-MY-ZSH

sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"

We should install a theme called Powerlevel10k. Run:

git clone --depth=1 https://github.com/romkatv/powerlevel10k.git ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/themes/powerlevel10k

Then, type nano ~/.zshrc. This opens nano, a text editor.

Edit the line where it says, ZSH_THEME="robbyrussell" to ZSH_THEME="powerlevel10k/powerlevel10k".

Restart Cmder.

After that, it automatically runs p10k configure. This asks some questions, just follow whatever is told on the screen. To achieve the result above, use the Rainbow Prompt style. I recommend turning on Instant Prompt. You can read more about it here. Also, you can turn on Transient Prompt. You can read more about it here.

At this point, my ~/.zshrc looks like this (from the authors standpoint)

# Enable Powerlevel10k instant prompt. Should stay close to the top of ~/.zshrc.
# Initialization code that may require console input (password prompts, [y/n]
# confirmations, etc.) must go above this block; everything else may go below.
if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then
  source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh"
fi
# If you come from bash you might have to change your $PATH.
# export PATH=$HOME/bin:/usr/local/bin:$PATH
# Path to your oh-my-zsh installation.
export ZSH="/c/Users/AnotherUser.APPLE.000/.oh-my-zsh"
# Set name of the theme to load --- if set to "random", it will
# load a random theme each time oh-my-zsh is loaded, in which case,
# to know which specific one was loaded, run: echo $RANDOM_THEME
# See https://github.com/ohmyzsh/ohmyzsh/wiki/Themes
ZSH_THEME="powerlevel10k/powerlevel10k"
# Set list of themes to pick from when loading at random
# Setting this variable when ZSH_THEME=random will cause zsh to load
# a theme from this variable instead of looking in $ZSH/themes/
# If set to an empty array, this variable will have no effect.
# ZSH_THEME_RANDOM_CANDIDATES=( "robbyrussell" "agnoster" )
# Uncomment the following line to use case-sensitive completion.
# CASE_SENSITIVE="true"
# Uncomment the following line to use hyphen-insensitive completion.
# Case-sensitive completion must be off. _ and - will be interchangeable.
# HYPHEN_INSENSITIVE="true"
# Uncomment the following line to disable bi-weekly auto-update checks.
# DISABLE_AUTO_UPDATE="true"
# Uncomment the following line to automatically update without prompting.
# DISABLE_UPDATE_PROMPT="true"
# Uncomment the following line to change how often to auto-update (in days).
# export UPDATE_ZSH_DAYS=13
# Uncomment the following line if pasting URLs and other text is messed up.
# DISABLE_MAGIC_FUNCTIONS="true"
# Uncomment the following line to disable colors in ls.
# DISABLE_LS_COLORS="true"
# Uncomment the following line to disable auto-setting terminal title.
# DISABLE_AUTO_TITLE="true"
# Uncomment the following line to enable command auto-correction.
# ENABLE_CORRECTION="true"
# Uncomment the following line to display red dots whilst waiting for completion.
# COMPLETION_WAITING_DOTS="true"
# Uncomment the following line if you want to disable marking untracked files
# under VCS as dirty. This makes repository status check for large repositories
# much, much faster.
# DISABLE_UNTRACKED_FILES_DIRTY="true"
# Uncomment the following line if you want to change the command execution time
# stamp shown in the history command output.
# You can set one of the optional three formats:
# "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
# or set a custom format using the strftime function format specifications,
# see 'man strftime' for details.
# HIST_STAMPS="mm/dd/yyyy"
# Would you like to use another custom folder than $ZSH/custom?
# ZSH_CUSTOM=/path/to/new-custom-folder
# Which plugins would you like to load?
# Standard plugins can be found in $ZSH/plugins/
# Custom plugins may be added to $ZSH_CUSTOM/plugins/
# Example format: plugins=(rails git textmate ruby lighthouse)
# Add wisely, as too many plugins slow down shell startup.
plugins=(git zsh-autosuggestions zsh-syntax-highlighting)
source $ZSH/oh-my-zsh.sh
# User configuration
# export MANPATH="/usr/local/man:$MANPATH"
# You may need to manually set your language environment
# export LANG=en_US.UTF-8
# Preferred editor for local and remote sessions
# if [[ -n $SSH_CONNECTION ]]; then
#   export EDITOR='vim'
# else
#   export EDITOR='mvim'
# fi
# Compilation flags
# export ARCHFLAGS="-arch x86_64"
# Set personal aliases, overriding those provided by oh-my-zsh libs,
# plugins, and themes. Aliases can be placed here, though oh-my-zsh
# users are encouraged to define aliases within the ZSH_CUSTOM folder.
# For a full list of active aliases, run `alias`.
#
# Example aliases
# alias zshconfig="mate ~/.zshrc"
# alias ohmyzsh="mate ~/.oh-my-zsh"
#source /usr/share/git/completion/git-completion.sh
#ZSH_THEME="powerlevel10k/powerlevel10k"
#parse_git_branch() {
 #git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
#}
#PROMPT_USER="\[\033[32m\]\u@\h\[\033[00m\]"
#PROMPT_DIR="\[\033[33m\]\w\[\033[00m\]"
#PROMPT_BRANCH="\[\033[35m\]\$(parse_git_branch)\[\033[00m\]"
#export PS1="$PROMPT_USER $PROMPT_DIR$PROMPT_BRANCH"$'\n$ '
# To customize prompt, run `p10k configure` or edit ~/.p10k.zsh.
[[ ! -f ~/.p10k.zsh ]] || source ~/.p10k.zsh

Note that I’ve added two extra plugins (look for the plugins=... line), zsh-autosuggestions and zsh-autocomplete. You can copy this and paste this to nano editor while editing ~/.zshrc . But you do need to install them. To do that, run:

git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting
git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions

You can learn more about them here and here

After that, restart your terminal.

Bash Aliases on ZSH

For ZSH aliases, I use the a custom file in ~/.oh-my-zsh/custom/aliases.zsh - if/when you upgrade OH-MY-ZSH your aliases will not be messed with.

File: ${HOME}/.oh-my-zsh/custom/aliases.zsh

alias vi="vim"
alias vizsh="vim ~/.zshrc"
alias vizshaliases="vim ~/.oh-my-zsh/custom/aliases.zsh"
alias szsh="source ~/.zshrc"

Run source ~/.zshrc and this will implement your modifications to OH-MY-ZSH, you can now run szsh to source the changes anytime you make modifications to ZSH or OH-MY-ZSH

  • A quick way to move your BASH ~/.bash_aliases to this format, just copy the file over:

    cp ~/.bash_aliases ~/.oh-my-zsh/custom/aliases.zsh
  • Then source ~/.zshrc to start using them

Moving SSH configs from Windows over to MSYS2

I had Windows 10 x64 configured for SSH pretty well (SSH config, authorized_keys, SSH keys, etc)

Inside a new MSYS2::MSYS2 shell (ZSH)

cd
mkdir .ssh
cp /c/Users/<USERNAME>/.ssh/* .
cp /c/Users/<USERNAME>/.ssh/.* .

This portion of my configuration is related to how pass works with Gitea on my NAS server

Host 192.168.XXX.XXX
    Hostname 192.168.XXX.XXX
    IdentityFile ~/.ssh/id_ed25519-username-gitea
    PreferredAuthentications publickey
    IdentitiesOnly yes
    User git

Setup GPG

Useful instructions

Run initial command to get things going:

gpg -k
gpg -K

Copied my Windows User's %APPDATA%\gnupg\gpg.conf to ~/.gpg/gpg.conf

ls -al /c/Users/<USERNAME>/AppData/Roaming/gnupg
cp /c/Users/<USERNAME>/AppData/Roaming/gnupg/gpg.conf ~/.gnupg

Backup your private and public key (in Windows command shell)

$ gpg --export-secret-keys --armor <fingerprint> > privkey.asc
$ gpg --export --armor <fingerprint> > pubkey.asc

In MSYS2 from ZSH command prompt, import your private key and public key

gpg --import privkey.asc
gpg --import pubkey.asc

Using password-store with git repository synching | Raw

Link to useful instructions: https://gist.github.com/abtrout/d64fb11ad6f9f49fa325

Setup git in MSYS2 to use the email and username of your choosing

git config --global user.email "[email protected]"
git config --global user.name "[email protected]"

Clone your ~/.password-store that you've previously setup

git clone [email protected]:username/passwordDB.git .password-store

Test some things

pass ls wifi
pass git pull

Tools for migrating from password store to bitwarden (vaultwarden)

https://github.com/xPMo/bwutil

pass2bw:
A tool to import zx2c4 password store into Bitwarden. It is rough around the edges, since I wrote it for the way I use password-store. Most of my files looked like this:

https://bitwarden.com/help/article/cli/

In a Cmder Windows CMD shell

choco install bitwarden-cli -y

Then bw works in MSYS2!

❯ bw
	Usage: bw [options] [command]
Options:
  --pretty                                    Format output. JSON is tabbed with two spaces.
  --raw                                       Return raw output instead of a descriptive message.
  --response                                  Return a JSON formatted version of response output.
  --cleanexit                                 Exit with a success exit code (0) unless an error is thrown.
  --quiet                                     Don't return anything to stdout.
  --nointeraction                             Do not prompt for interactive user input.
  --session <session>                         Pass session key instead of reading from env.
  -v, --version                               output the version number
  -h, --help                                  display help for command

Commands:
  login [options] [email] [password]          Log into a user account.
  logout                                      Log out of the current user account.
  lock                                        Lock the vault and destroy active session keys.
  unlock [options] [password]                 Unlock the vault and return a new session key.
  sync [options]                              Pull the latest vault data from server.
  generate [options]                          Generate a password/passphrase.
  encode                                      Base 64 encode stdin.
  config [options] <setting> [value]          Configure CLI settings.
  update                                      Check for updates.
  completion [options]                        Generate shell completions.
  status                                      Show server, last sync, user information, and vault status.
  list [options] <object>                     List an array of objects from the vault.
  get [options] <object> <id>                 Get an object from the vault.
  create [options] <object> [encodedJson]     Create an object in the vault.
  edit [options] <object> <id> [encodedJson]  Edit an object from the vault.
  delete [options] <object> <id>              Delete an object from the vault.
  restore <object> <id>                       Restores an object from the trash.
  move <id> <organizationId> [encodedJson]    Move an item to an organization.
  confirm [options] <object> <id>             Confirm an object to the organization.
  import [options] [format] [input]           Import vault data from a file.
  export [options] [password]                 Export vault data to a CSV or JSON file.
  share <id> <organizationId> [encodedJson]   --DEPRECATED-- Move an item to an organization.
  send [options] <data>                       Work with Bitwarden sends. A Send can be quickly created using this command or subcommands can be used to fine-tune the Send
  receive [options] <url>                     Access a Bitwarden Send from a url
  help [command]                              display help for command

  Examples:

	bw login
	bw lock
	bw unlock myPassword321
	bw list --help
	bw list items --search google
	bw get item 99ee88d2-6046-4ea7-92c2-acac464b1412
	bw get password google.com
	echo '{"name":"My Folder"}' | bw encode
	bw create folder eyJuYW1lIjoiTXkgRm9sZGVyIn0K
	bw edit folder c7c7b60b-9c61-40f2-8ccd-36c49595ed72 eyJuYW1lIjoiTXkgRm9sZGVyMiJ9Cg==
	bw delete item 99ee88d2-6046-4ea7-92c2-acac464b1412
	bw generate -lusn --length 18
	bw config server https://bitwarden.example.com
	bw send -f ./file.ext
	bw send "text to send"
	echo "text to send" | bw send
	bw receive https://vault.bitwarden.com/#/send/rg3iuoS_Akm2gqy6ADRHmg/Ht7dYjsqjmgqUM3rjzZDSQ

Then it becomes possible to use tools to convert password store passwords, (T)OTPs, etc to Bitwarden format:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment