shell tips

shell tips

Command substitution

You could use $(command) or `command` to provide the output of a command as an argument to another command.
I guess I made it confusing, so let me show you an example:

To create a file with today’s date as its filename and edit it directly, you can:

vim $(date +%Y-%m-%d).md

!!

Suppose you executed a command. You could get the previous command using !!.
I’ll show you an example:

Suppose you want to see if any orphaned packages exist in the system, and then, remove it. You could do:

pacman -Qdttq # prints orphaned packages in the system
doas pacman -Rns $(pacman -Qdttq)

Instead, you could do:

pacman -Qdttq # prints orphaned packages in the system
doas pacman -Rns $(!!) # i prefer `!!` doe

!$

If !! refers to the previous command, !$ refers to the last word in the previous command.
Example:

mv ~/test.md Documents/wiki/tips.md
vim !$ # equal to vim Documents/wiki/tips.md

!:n

If !$ refers to the last word in the previous command, !:n can be used to target any term in the previous command.
Just a reminder, the number starts with 0, i.e, the first term is numbered 0, not 1.

Example:

cp Documents/wiki/tips.md Documents/wiki/tips.md_bak
vim !:1 # equal to vim Documents/wiki/tips.md

Replace terms in previously executed command and re-execute it

Suppose you ran doas apt autoremove, but it errors out because you don’t have doas installed. Instead of going back, replacing doas with sudo, or even worse - typing the whole thing again, you could do:

!!:s/doas/sudo/

It resembles sed & vim syntax, so it’s a nice-to-have for me, at least.

Ctrl-Z & fg: Back From The Dead

Ctrl-Z suspends the current program running in your terminal and takes you back to the shell. Run fg to bring the program back.

Piping into clipboard

I copy command output directly into the clipboard using xclip:

cat file.md | xclip -sel c -r

-sel c copies the data onto the clipboard, and -r removes the trailing newline character at the end.

I have created an alias called copy to use in place of the xclip command:

~/.bashrc
alias copy="xclip -sel c -r"

Piping screenshots directly into the clipboard

With import command from imagemagick (only works in X.org):

import png:- | xclip -t image/png -sel c

realpath

The realpath command provides the full path of the mentioned file:

$ realpath file.md # OUTPUT: /home/user/Documents/file.md

I pipe its output into xclip or copy (as mentioned above) for quick copying:

realpath file.md | xclip -sel c -r
# OR
realpath file.md | copy

which

which is used to find the path of an executable:

$ which zsh # OUTPUT: /usr/bin/zsh

command -v zsh also works.

rev: Reverse text

echo hello world | rev # Output: dlrow olleh