Created
November 12, 2024 14:53
-
-
Save zwimer/32af95d496a668264169c02f11f1b0cf to your computer and use it in GitHub Desktop.
A few useful bash tricks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Random useful bash stuff: | |
1. . ^foo^bar - bash !! but replaces the first occurrence of foo with bar | |
2. !!:/gs/foo/bar - bash !! but replaces all occurrences of foo with bar | |
3. cd -4 = cd; cd; cd; cd. cd -- = cd; cd. cd - = cd; pwd (or use pushd and popd) | |
4. diff <(sort a) <(sort b) The output of sort a is pushed into a pipe which pretends to be a file for diff. This is process substitution | |
5. < foo grep bar | sort is the same as cat foo | grep bar | sort | |
6. $'\167' is the same as w - bash interprets octal! Also works with hex! | |
7. If you do echo !!:4 will echo the 4th argument of the last command. !$ is the last arg and !^ is the fist, !* is all. | |
8. !g will autocomplete to the last command run that began with g | |
9. set -o vi - enable vim bindings for bash | |
10. **/* is all files within all folders starting at . | |
11. shopt -s cmdhist multi-line commands will be stored in history as one command | |
12. escape . will insert the last argument from your last command | |
13. ls a?b will ls all 3 character files starting with a and ending with b. | |
14. !?foo?:p will print the last command that used foo | |
15. set completion-ignore-case on makes bash easier | |
16. Combinations of control, alt, and characters do a lot of stuff with auto complete. | |
17. % - stuff about jobs | |
18. $- flag options | |
19. $_ Current terminal | |
20. $* expands to a single string while $@ expands to multiple arguments | |
21. cat << EOF and cat <<- EOF, etc are heredocs! Multi-line bash input without \s! | |
22. Bash variable expansion with substitution. ${FOO//Pattern/Replacement} Expand a variable while replacing certain characters in the expansion with others! (There are a dozen variations of this, like one that replaces only the first occurrence) | |
23. ls a[bc] will ls ab only if ab exists and ls ac only if ac exists | |
24. touch a{0..9} will touch 0... touch 9 | |
25. FOO="a b"; echo c d ${FOO#a} prints c d b | |
26. &> is shorthand for 2>&1 > . Similarly |& and &>> are shorthand. | |
27. Adding a trailing space to an alias forces that alias to respect other aliases; e.x. alias x='xargs '; alias c=cat; echo a.c | x c works only with the trailing space | |
These are just some off the top of my head, feel free to add a few. Just thought they were worth sharing :slightly_smiling_face: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also: https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html