ZSH Aliases
thorsten-hans.com
thorsten-hans.com
If you're giving a presentation, please give the actual commands people need to type, even if that's a little more typing for you. There are tools to help you auto-type each line of a demo, if needed. Reduce the amount of confusion and translation people need to go through to understand your presentation.
Similarly, turn off any fonts that create symbolic ligatures, so people know what symbols to actually type.
Avoid anything unnecessary that increases the distance needed for understanding between you and your audience.
Modern versions of Fish has both abbreviations and aliases. Personally, I prefer aliases for providing default arguments to commands (e.g. turning on colorized output), but prefer abbreviations for timesavers like the `gc` above.
alias -s {ape,avi,flv,m4a,mkv,mov,mp3,mp4,mpeg,mpg,ogg,ogm,wav,webm}=mpv
as opposed to defining them one at a time.(Self, you idiot)
cd'ing into a directory on the fly without even thinking about paths and just opening files by name is powerful juju
Together With AUTOCD, this feels like it shouldn't be possible...but it is.
alias -g G='| grep'
alias -g R='| rg'
alias -g L='| less'
alias -g V='| vim -'
alias -g S='| subl'
And if I want Zsh to auto-expand it out to type the full command (after pressing space), add this to end of your .zshrc: globalias() {
if [[ $LBUFFER =~ '[A-Z0-9]+$' ]]; then
zle _expand_alias
zle expand-word
fi
zle self-insert
}
zle -N globalias
bindkey " " globalias # space key to expand globalalias
Identical examples: grep -rw --exclude-dir={test,build} 'throw' L
grep -rw --exclude-dir={test,build} 'throw' | less alias -s git="git clone"Overwriting a command-line tool with no other arguments seems like a bad idea.
The only time I use the full URL is the initial cloning, and the remote name thereafter. But if you use the full URL in another scenario, yes, this may interfere.
- "git", alone isn't going to be hooked.
- you can do "cd .git".
- even if you have 'autocd' option set, you can '.git' and it will do "cd .git".
I'm not saying it's even a good practice, but I find it kinda cool, when using this feature in a way it's probably not intended for, you start thinking in 'what might happen inside'. https://github.com/zsh-users/zsh.git
Into your shell, and have it automatically get translated into git clone https://github.com/zsh-users/zsh.git
It has no effect at all on your ability to run regular git commands.happy hacking :)
The example
alias dev="cd ~/dev/"
alias personal="cd ~/dev/thorstenhans"
alias business="cd ~/dev/thinktecture"
Becomes export dev=~/dev
export personal=~/dev/thorstenhans
export business=~/dev/thinktecture
And now thanks to the way ZSH handles directories, you can still simply change directory with $ ~dev
$ ~personal
$ ~business
and it'll work as before but it also allows you to treat it as a fully qualified directory in other commands which I find exceedingly useful $ tree ~dev
$ cat ~personal/index.html
$ rm -rf ~business/secret-documents hash -d dev=~/dev
hash -d personal=~/dev/thorstenhans
...
Nothing else is needed. $ docker run --workdir=$dev foo
in these cases `--workdir=~dev` is not expanded and fails as docker does not understand your alias.- alias -g G="| grep " (`cat test.txt G some_words`) - alias -g CC="| pbcopy " (`cat test.txt CC`) - alias -g "?"="| fzf " (`ls -l ?`) - alias -g X="| xargs " (`ls -l X rm`), probably my favorite (makes xargs kinda look like a pipe) - alias -g Y="| yank "
They compose well, too.
- Pick some file to delete from `git status`: `git status Y X rm`
alias -g FORI='| while read i ; do '
alias -g IROF='; done ' alias -g Y="| yank -- cat "
[0] https://github.com/mptre/yankCould be clearer, basically it means that if it's part of a pipe, it's going to print to stdout instead of copying to the clipboard
> source $HOME/.zshrc
.zshrc isn't the only startup file, if you place everything there you're likely doing it wrong and should split things like some environment settings to $ZDOTDIR/.zshenv.
Better way to reload startup changes:
alias reload='exec zsh -l' alias reload="exec -l $SHELL"
Which I copied from somewhere, I don't know how specific it is but maybe it helps someone :) export SHELL=/sbin/nologin # or /usr/sbin/nologin, or equivalent on your system
exec -l $SHELL
You want zsh, so just use zsh.As for -l, exec zsh -l and exec -l zsh both replace the current shell with a login zsh, so they are effectively the same.
# Load Order Interactive Interactive Script
# Startup Only login Always
# ------------- ----------- ----------- ------
# /etc/zshenv 1 1 1
# ~/.zshenv 2 2 2
# /etc/zprofile 3
# ~/.zprofile 4
# /etc/zshrc 5 3
# ~/.zshrc 6 4
# /etc/zlogin 7
# ~/.zlogin 8
#
# Shutdown
# ------------- ----------- ----------- ------
# ~/.zlogout 9
# /etc/zlogout 10
#
# Note: ZSH seems to read ~/.profile as well, if ~/.zshrc is not present.Technically it's $ZDOTDIR/…
Also note from the official documentation:
> `.zprofile' is meant as an alternative to `.zlogin' for ksh fans; the two are not intended to be used together
$ alias -s js=node
$ echo "console.log('Hello world')" > demo.js
$ demo.js
Hello worldI can see opening up in an editor as useful shortcut. But actually executing code without an executable bit seems a bit more dangerous.
alias -s sh='_c(){ curl -sk $1 | sudo bash };_c'
Wait. Improved. alias -s sh='_c(){ [[ -f $1 ]] && sudo bash $1 || curl -sk $1 | sudo bash };_c' echo :js:E::0::/usr/bin/node: >/proc/sys/fs/binfmt_misc/registerFor example, I use:
``` alias open=xdg-open ```
To call the real open command, I can use \open.
I know that there is oh-my-posh, but it lacks such plugins. Do you know any workaround?
##
# PSReadLine, see https://github.com/PowerShell/PSReadLine
##
## behaviour of Tab key autocomplete
Set-PSReadlineKeyHandler -Key Tab -Function MenuComplete
## From docs:
## With these bindings, up arrow/down arrow will work like PowerShell/cmd if the
## current command line is blank. If you've entered some text though, it will
## search the history for commands that start with the currently entered text.
##
## Like zsh completion.
Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward
Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward
These will allow you to autocomplete previous commands from the tidpids you already types, so it no longer searches linearly through the history.
I also use: Import-Module posh-git
Import-Module oh-my-posh
Set-Theme AgnosterHere is the other content:
# For Agnoster theme, "user@host" will be hidden if user==DefaultUser
$DefaultUser = "<YOUR USERNAME>"
function vim ($File){
bash -c "vim $File"
}
New-Alias pi ipython
# git diff output uses less; it will be buggy without utf8
$env:LESSCHARSET='UTF-8'
# console output, e.g, when writing git diff output to file using pipe: | Out-File
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8alias -g NF='./*(oc[1])'
This points to the newest file/dir in my current dir, and it is very easy for me to untar a downloaded file and then cd into it without caring about the name of the file/dir.
tar xf NF; cd NF
mv ~/Downloads/[C-x m] /tmp
or even within files that match what I've typed already:
tail /logs/pho[C-x m]
What I'm talking about is typing 'sls logs <tab>' and having tab completion for the deployed functions when typed in the root of the repo containing the serverless.yml file.
https://github.com/larrybolt/zsh-aliases/blob/master/serverl...
At my first company, the onboarding script included switching to ZSH+OMZ. I knew it changed the shell, but thought it was just theming - not much. A year later, switched companies, didn't install it. Don't know how I lived without it. It is such an amazing productivity update to shell life I consider it a must on every machine.
alias venv=". venv/bin/activate"
Just cd to a project root and venv :) alias venv='python3 -m venv venv && source venv/bin/activate && pip install --upgrade pip setuptools -q'
And then ae and de to activate/deactivate a venv: alias ae='source venv/bin/activate'
alias de='deactivate' setopt autocd
hash -d dev=~/dev
Now I can just use `~dev` to `cd ~/dev` but I can also do `~dev/foo/bar/baz` etc.e.g. `z p` might take you to ~/projects if you've been there recently.
For example if I'm in "/Documents/Dotfiles", but want to go to "/Documents/Blog". Doing the "../" dance is tedious as hell.
% Documents/Dotfiles
[~/Documents/Dotfiles] % ../Blog
This does the trick.
export SITES=$HOME/Sites
# Plural to cd and list contents
alias sites="cd $SITES; ll"
# Singular to access a particular project
site() { cd $SITES/$1; }
# Autocomplete function
_site() { _directories -W $SITES -/; }
compdef _site site
It works from within any directory, which is nice. site f[tab][enter]
takes me to $SITES/foo/Although I do wish I could pass a flag that didn’t open it, as sometimes I do want to append or overwrite a file without the fuss of an editor.
% foo.jpg
# launches image viewer
% cp foo.jpg bar.jpg
# unaffected
What's the benefit of suffix aliases compared with setting up the associations? You only save two keystrokes if you have a single-letter alias (for xdg-open on linux).
BTW. Anyone is really using the colorscheme like in article ?
https://thorsten-hans.com/assets/images/posts/2020/zsh-alias...
For example if I set the following alias:
alias hello = '~/Docuemnts'
It would be nice if I could then execute hello/world to take me to ~/Documents/world but it requires hardcoding.Guess I could play around with functions and arguments to solve this.
Also, apparently you can add this to zsh with a plugin: https://github.com/momo-lab/zsh-abbrev-alias
I keep all my code in ~/code
$ c # cd to ~code
$ c pr<tab> # tab complete to c projectname
$ c projectname # cd to ~/code/projectname
This is pretty simple in zsh
# c to cd to ~/code
c() { cd ${CODE_DIRECTORY}/$1; }
# tab complete c against code
_c() { _files -W ${CODE_DIRECTORY} -/; }
compdef _c c
(Note: CODE_DIRECTORY is just an env var for ~/code)
I use this all the time and I use h to do the same for my home directory
https://github.com/gpspake/dotfiles/blob/master/zsh/gpspake/...
hello=~/Documents
Then: cd ~hello/world
Or omitting `cd` (requires `setopt auto_cd`): ~hello/world
And with `setopt cdable_vars`: hello/word
This also works with tab completion: hello/<TAB> hash -d hello=~/Documents
~hello/world
The shortened names also show up in your PROMPT if it is using %~ to display cwd. $ hash -d hello=$HOME/Documents
$ cd ~hello/world && pwd
/home/user/Documents/worldBut if you're not ready to switch yet and still want to use bash for now, set this to remove the deprecation warning:
export BASH_SILENCE_DEPRECATION_WARNING=1
alias ls='exa -l'
alias gits='git status' alias ls="exa --color auto --all --group-directories-first --long --group --header --modified --sort=name --git --time-style=long-iso --classify"
That should give you a gorgeous directory list. # ~/.config/git/config
[alias]
s = status
d = diff
ds = diff --staged
# ~/.zshrc
alias g=git
$ g s
$ g ds
I think I have an alias for every letter of the alphabet.Tldr: 1. aliases, 2. suffix aliases, 3. global aliases
However, the os-specific aliases became more and more important to me due to GitHub and VisualStudio Codespaces. Targeting different operating systems is quite important to me.
But technically it's just a regular alias. (Which is also mentioned in the corresponding paragraph)
>You have seen four different types of ZSH aliases that will boost your productivity
`four` in these two lines is typo or intentional? Because the title says `5 Types Of ...`
> The registration of aliases with parameters looks pretty similar to a function definition in regular programming languages.
Well that's because it is a function definition in this programming language, no?
Furthermore, this breaks down when you, say, use `alias` to view all your aliases. It won't show the functions, because they are not aliases.
alias -s txt='less -rE'I have a habit of cleaning up the workspace in my machine. This alias saved me a 1000 times already.
https://thorsten-hans.com/5-types-of-zsh-aliases
if your ad blocker is barfing on whatever bitly-based tracking doodad was submitted instead.
also, if you use aliases for commands that you use a lot, it is better to remember how to correctly type the command.
I’ve added extensive aliases to my shell and it saves me mountains of time. If they break, so what? You fix them? It’s computers; everything breaks eventually.
I’m appalled at the idea of trading constant convenience against some hypothetical and unspecified future breakage.