when I forget to include sudo in my command:
sudo !!
From Wikipedia, the free encyclopedia
Linux is a family of open source Unix-like operating systems based on the Linux kernel, an operating system kernel first released on September 17, 1991 by Linus Torvalds. Linux is typically packaged in a Linux distribution (or distro for short).
Distributions include the Linux kernel and supporting system software and libraries, many of which are provided by the GNU Project. Many Linux distributions use the word "Linux" in their name, but the Free Software Foundation uses the name GNU/Linux to emphasize the importance of GNU software, causing some controversy.
Community icon by Alpár-Etele Méder, licensed under CC BY 3.0
when I forget to include sudo in my command:
sudo !!
Also if you make a typo you can quickly fix it with ^, e.g.
ls /var/logs/apache
^logs^log
To add to this one, it also supports more than just the previous command (which is what !! means), you can do like sudo !453 to run command 453 from your history, also supports relative like !-5. You can also use without sudo if you want which is handy to do things like !ls for the last ls command etc. Okay one more, you can add :p to the end to print the command before running it just in case like !systemctl:p which can be handy!
Similar-ish for quickly editing last command:
fc
I learned about this through Bread On Penguins, she did a vid on useful commands
I use $_ a lot, it allows you to use the last parameter of the previous command in your current command
mkdir something && cd $_
nano file
chmod +x $_
As a simple example.
If you want to create nested folders, you can do it in one go by adding -p to mkdir
mkdir -p bunch/of/nested/folders
Good explanation here:
https://koenwoortman.com/bash-mkdir-multiple-subdirectories/q
Sometimes starting a service takes a while and you're sitting there waiting for the terminal to be available again. Just add --no-block to systemctl and it will do it on the background without keeping the terminal occupied.
systemctl start --no-block myservice
Is there a version of $_ that works with mv? It just keeps renaming my files to "filedir," I'm trying sort through a directory and move some files to another for keeping, be easier if I could do:
mv picture1.jpg /path/to/keepdirectory
then do something like
mv picture2.jpg $_
And so on. But with that I'd just be renaming all my photos "filedir" instead of moving them lol.
For interactive editing, the keybind alt+. inserts the last argument from the previous command. Using this instead of $_ has the potential to make your shell history a little more explicit. (vim $_ isn't as likely to work a few commands later, but vim actual_file.sh might)
Ctrl-z to suspend the running program.
bg to make it continue running in the background.
jobs to get an overview of background programs.
fg to bring a program to the foreground.
and
disown
to keep background jobs alive when you close the terminal.
It isn't a command but an application. I cannot do my work without it.
screen
I prefer tmux, but yes. Both do a great job in helping me manage my terminal sessions.
tmux is based
Tmux is good because I can have a little window with a bonsai in it and another little window for the matrix. Sometimes I even leave a window for typing in commands.
I only recently started using C-r to search in the command history. Game changer!
Want an even bigger game changer? fzf combined with control-r.
Enjoy.
https://atuin.sh/ does one better. history with context: $PWD, $HOST, time. There's a bunch of other bells and whistles, but they're easy to ignore to get an noninvasive upgrade to ctrl+R
The watch command is very useful, for those who don't know, it starts an automated loop with a default of two seconds and executes whatever commands you place after it.
It allows you to actively monitor systems without having to manually re-run your command.
So for instance, if you wanted to see all storage block devices and monitor what a new storage device shows up as when you plug it in, you could do:
watch lsblk
And see in real time the drive mount. Technically not "real time" because the default refresh is 2 seconds, but you can specify shorter or longer intervals.
Obviously my example is kind of silly, but you can combine this with other commands or even whole bash scripts to do some cool stuff.
find /path/to/starting/dir -type f -regextype egrep -regex 'some[[:space:]]*regex[[:space:]]*(goes|here)' -exec mv {} /path/to/new/directory/ \;
I routinely have to find a bunch of files that match a particular pattern and then do something with those files, and as a result, find with -exec is one of my top commands.
If you're someone who doesn't know wtf that above command does, here's a breakdown piece by piece:
find - cli tool to find files based on lots of different parameters/path/to/starting/dir - the directory at which find will start looking for files recursively moving down the file tree-type f - specifies I only want find to find files.-regextype egrep - In this example I'm using regex to pattern match filenames, and this tells find what flavor of regex to use-regex 'regex.here' - The regex to be used to pattern match against the filenames-exec - exec is a way to redirect output in bash and use that output as a parameter in the subsequent command.mv {} /path/to/new/directory/ - mv is just an example, you can use almost any command here. The important bit is {}, which is the placeholder for the parameter coming from find, in this case, a full file path. So this would read when expanded, mv /full/path/of/file/that/matches/the/regex.file /path/to/new/directory/\; - This terminates the command. The semi-colon is the actual termination, but it must be escaped so that the current shell doesn't see it and try to use it as a command separator.I'd say that journalctl is not only boot, but every service that runs on the computer has its logs collected through it, so you can use it as journalctl --grep="your regex". You can also add -k to check kernel logs, -b -n to check nth precedent boot or -b n to check the absolute nth boot. There is a lot that you can check with it and it is quite nice :)
Otherwise, I like eza as an ls replacement, or batcat as a human friendly cat
Don't forget the almighty:
journalctl -fu <servicename>
And yes, I am always reading that as "fuck you, service".
ripgrep has mostly replaced grep for me, and I am extremely conservative about replacing core POSIX utilities - muscle memory is critical. I also tend to use fd, mainly because of its forking -x, but its advantages over find are less stark þan rg's improvements over grep.
nnn is really handy; I use it for everything but the most trivial renames, copies, and moves - anyþing involving more þan one file. It's especially handy when moving files between servers because of þe built-in remote mounting.
I'm a big enjoyer of pushd and popd
so if youre in a working dir and need to go work in a different dir, you can pushd ./, cd to the new dir and do your thing, then popd to go back to the old dir without typing in the path again
Nice! I didn't know that one.
You can also cd to a directory and then do cd - to go to the last directory you were in.
parallel, easy multithreading right in the command line. This is what I wish was included in every programming language's standard library, a dead simple parallelization function that takes a collection, an operation to be performed on the members of that collection, and optionally the max number of threads (should be the number of hardware threads available on the system by default), and just does it without needing to manually set up threads and handlers.
inotifywait, for seeing what files are being accessed/modified
tail -F, for a live feed of a log file
Finally, a more complex command I often find myself repeatedly hitting the up arrow to get:
find . -type f -name '*' -print0 | parallel --null 'echo {}'
Recursively lists every file in the current directory and uses parallel to perform some operation on them. The {} in the parallel string will be replaced with the path to a given file. The '*' part can be replaced with a more specific filter for the file name, like '*.txt'.
I can recommend tmux also as an alternative to screen
should be the number of hardware threads available on the system by default
No, not at all. That is a terrible default. I do work a lot on number churning and sometimes I have to test stuff on my own machine. Generally I tend to use a safe number such as 10, or if I need to do something very heavy I'll go to 1 less than the actual number of cores on the machine. I've been burned too many times by starting a calculation and then my machine stalls as that code is eating all CPU and all you can do is switch it off.
sudo shutdown 0
Prevents 99% of bugs and mistakes
Another one of my favorite is ctrl+r to quickly search for a previous command.
Then type in a word from the command you are looking for and then hit tab to find the right command if there is more than one with that word.
nc is useful. For example: if you have a disk image downloaded on computer A but want to write it to an SD card on computer B, you can run something like
user@B: nc -l 1234 | pv > /dev/$sdcard
And
user@A: nc B.local 1234 < /path/to/image.img
(I may have syntax messed up--also don't transfer sensitive information this way!)
Similarly, no need to store a compressed file if you're going to uncompress it as soon as you download it---just pipe wget or curl to tar or xz or whatever.
I once burnt a CD of a Linux ISO by wgeting directly to cdrecord. It was actually kinda useful because it was on a laptop that was running out of HD space. Luckily the University Internet was fast and the CD was successfully burnt :)
Not a command but the tab key for auto complete. This made it much easier for me.
I get a lot of milage out of the line editing commands. I think they are Emacs based and optional... but like Ctrl k, Ctrl u, Ctrl a.
systemd-run lets you run a command under some limitations, ie
systemd-run --scope -p MemoryLimit=1000M -p CPUQuota=20% ./heavyduty.sh
https://blog.sanctum.geek.nz/series/unix-as-ide/
# list all recursive files sorted by size
$ fd -tf "" -x du -h | sort -h
8.0K ./asdfrc
20K ./nvim/lua/lush_theme/bleak.lua
32K ./alacritty.yml
# find files by extension
$ fd -e lua
nvim/colors/bleak.lua
nvim/init.lua
nvim/lua/config/autocmds.lua
# list found files in tree view
$ fd -e lua | tree --fromfile
.
└── nvim
├── colors
│ └── bleak.lua
├── init.lua
# Run "npm test" when a file changes in the src or test directories
$ fd src test | entr -- npm test
# find out how often you use each command
history | cut -d " " -f 1 | sort | uniq -c | sort -n | tail -n 10
80 rm
81 lsd
107 asdf
136 npx
161 find
176 fd
182 cd
185 rg
247 brew
250 nb
465 npm
867 git
Search for github repos of dotfiles and read through people's shell profiles, aliases, and functions. You'll learn a lot.
pkill journalctl -b nvtop tail are great but I like:
LANGUAGE=en_GB LC_ALL=en_GB.UTF-8 LANG=en_GB.UTF-8 <your GUI program> to run a GUI program in English for more universal compatibility for helping newbies and creating/reading non-terminal based documentation
I'm not much of a one-liner collector but I like this one:
vim +copen -q <(grep -r -n <search> .)
which searches for some string and opens all instances in vim's quickfix list (and opens the quickfix window too). Navigate the list with :cn and :cn. Complex-ish edits are the obvious use case, but I use this for browsing logs too.
Neovim improves on this with nvim -q - and [q/]q, and plenty of fuzzy finder plugins can do a better version using ripgrep, but this basic one works on any system that has gnu grep and vim.
Edit:
This isn't exactly a command, but I can't imagine not knowing about this anymore:
$ man grep
/ -n # double space before the dash!
brings you directly to the documentation of the -n option. Not the useless synopsis or any other paragraphs that mention -n in passing, but the actual doc for this option (OK, very occasionally it fails due to word wrap, but assuming the option is documented then it works 99% of the time).
ripgrep
fzf is great for quickly finding files e.g. in large code repositories.
tcpdump can help diagnose network issues.
Bash/ZSH aliases are invaluable for commands that you run often. I use micro as my terminal editor so I have alias m for micro and sm for sudo micro. Just 2 of maybe a dozen aliases I use. Docker has quite a large list of aliases with ZSH. Super super useful.
List open files
sudo lsof -i -P
Network traffic by hardware
sudo tcpdump -i en1 -nn -s0
Current processes
top -l 1
Something that really improved my life was learn to properly use find, grep, xargs and sed. Besides that, there are these two little 'hacks' that are really handy at times...
1- find out which process is using some local port (i.e. the modern netstat replacement):
$ ss -ltnp 'sport = :<port-number>'
2- find out which process is consuming your bandwidth:
$ sudo nethogs