mdk.fr/content/blog/2021-bash.md

140 lines
2.5 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
Title: How I use bash
Summary: This is how I use bash, as I presented it at « En attendant la PyCon Fr ».
---
# bash
I presented this as a lightnign talk at [« En attendant la PyCon
Fr »](https://discuss.afpy.org/t/en-attendant-la-pyconfr-du-15-avril-2021/222/),
there's [a video
(in french)](https://dl.afpy.org/en-attendant-la-pycon-fr-2020-2021/2021-04%20Bash%20-%20trucs%20&%20astuces%20-%20mdk.mp4).
How to read:
When I write `^A` it mean I press `Ctrl-A`, which is noted `C-a`
(bash/emacs notation).
`M-a` means `Meta-a` (it's left alt on current keyboards).
## I avoid singleline prompt
Because of the following issue:
PS1='$ '
printf "pouette"
ls^A
ls -l^A
Issue is: readline have two ways to move at the beginning of a line,
and have no way to know where the cursor is, and assume the line start
at column 0.
## Easy, daily, shortcuts
### Killing and Yanking from the killing stack
- `C-a C-k`: Move to the beginning, then kill the line.
- `C-y`, `M-y`: Yank and yank pop.
Example:
```
$ git push origin HEAD^A^Kgit commit -m "FIX"^A^Kgit add -u
C-y
Enter
C-y
M-y
Enter
```
### Moving
- `C-a` (beginning of line) `C-e` (end of line).
- `C-p` and `C-n`: like up and down arrows, to browse history.
Avoid `C-pC-pC-pC-pC-p` or `↑↑↑↑↑↑`, use `C-r`.
### Fixing typos
- `C-t` (swap chars), `M-t` (swap words).
- `M-l`, `M-u`, `M-c` (lowercase, uppercase, capitalize)
- `C-g` (abort)
### Cleaning
`C-l` (clear screen). Oh, if it's not enough, like after killing `sl`,
use `reset`, so `ENTER reset ENTER` to ensure you type it in a clear
line, or `C-a C-k reset ENTER` to avoid executing blindly.
### sudo !!
```bash
$ man bash | grep '!!'
!! Refer to the previous command. This is a synonym for `!-1'.
```
so:
```
$ apt upgrade
E: ... are you root?
$ sudo !!
sudo apt upgrade
...
```
### Globstar
`shopt -s globstar`:
```
$ rm **/*.md
```
same as:
```
$ find -name '*.md' -delete
```
example:
```
sed -i '1i#!/usr/bin/env python3' **/*.py
```
## Other shortcuts I use
And I like them for the nice symetry:
- `C-f` to move forward a char, `M-f` to move forward a word.
- `C-b` to move backward a char, `M-b` to move backward a word.
- `C-d` to delete a char, `M-d` to delete a word.
## Pipelines for the win!
```
$ man bash | grep -C1 C-a
Commands for Moving
beginning-of-line (C-a)
Move to the start of the current line.
```
## Subshells for the win!
```
emacs $(git grep -l PATTERN)
```
# Bonus
Those are the same in emacs, save brain space, use emacs.