Skip to main content
anthony

1 year ago

What are your favorite command line tips and tricks?!

We all have some favorite command line short cuts that help us move around quicker while operating in a Linux system or even a container.


What are your most favorite ones that you would share for someone looking to master the Linux command line?

Image of
1 year ago
sudo !!
Runs previous command with sudo (without retyping).
Thanks to: Engineer Man "8 super heroic Linux commands that you probably aren't using" - https://youtu.be/Zuwa8zlfXSY?t=41
Image of
1 year ago
Two that I use constantly are:

Up arrow to scroll through previous commands.

Tab for autocompletion, especially when referencing file paths.
Image of
1 year ago
tail and grep are big ones for me.  using tail to view things like the end of a log file or using grep to search makes the job easier when troubleshooting.
Image of
1 year ago

I'm always partial to a cheeky awk or sed 1-liner for  quick or easier editing..and you can't beat a  well formed vimrc https://github.com/amix/vimrc  however I couldn't live without tmux as that runs on all my hosts...(steep learning combo curve but after a while becomes second nature)!

Image of
1 year ago
ls and ll :)
Image of
1 year ago
For productivity tmux is one of the biggest imo, you can configure it to your needs really well. 
Also all the bash movement shortcuts i.e. alt+w to skip to next word, ctrl+w to delete it.
Image of pzona
pzona
1 year ago
One of my favs - you can do a reverse search for commands you've previously run with CTRL + r. If you ran a long iptables command, for example, that you don't want to re-type and it's too long ago to use the up key efficiently, you can press CTRL + r and start typing "iptables". If there are multiple results you can also keep pressing CTRL + r to page through all of them.

A great combination to use with the reverse search is inline commenting. Bash allows you to write comments with #, and that includes from the command line. So let's say you have an extremely long MySQL connection string. Rather than putting it in a text document and copy/pasting each time you can do this:

mysql -h myhost.com -u me -p -P 12345 --some-other-option #my-database

And then do the reverse search as described above, but search for your comment: CTRL + r, then begin typing "my-database." Sounds a bit tricky at first, but it's a massive time saver and it will save your "favorite commands" as long as they're in your Bash history.
Image of
1 year ago
@Toni I agree, Tmux is great. Here is my tmux cheet sheet that I made when I first started using it. I will sometime make cheetsheets like this and put them in my home directory.
###Tmux###

- C-b = [Ctrl]+[b]

Panes
- Navigate Panes    = C-b [Arrow]
- Panes horizonatal = C-b "
- Panes Vertical    = C-b %
- Closing Pane      = $exit  |or| C-d 

Windows
- Navigate windows  = C-b p |or| C-b n
- Switch to #       = C-b [#]
- Create window     = C-b c

Sessions
- Detach session    = C-b d
- Pick Session      = C-b D
- list sessions     = $tmux ls
- attach session    = $tmux attach -t 0
- rename session    = $tmux rename-session -t 0 [name]
- attach named ses  = $tmux attach -t [name]
- kill session      = $tmux kill-session -t [name]

More info
https://gist.github.com/MohamedAlaa/2961058

Image of adobrich
adobrich
1 year ago
One thing I've found useful is  !$
It's contents is the last part of the previous command.
As an example you could do this:

mkdir -p ./path/to/my/long/directory/chain
cd !$

Image of
1 year ago
For me it would be ctrl+r and history with grep so that i don't  need to waste time while running previous commands.
Image of
1 year ago
vimtutor helps me a lot to practice as I am building knowledge on Linux system.
Image of santhosh3431
santhosh3431
1 year ago
i always prefer to type ls -ltr or ls -Ralsi :)
Image of eube
eube
1 year ago
A personalized dotfiles. I have aliases for everything, from running installs to completely setting up a new install of Linux on my laptop.
Image of haritak
haritak
1 year ago
My fav are ^r, ^w, find and w -f
Image of vgedris
vgedris
1 year ago
  • cd -
    • To get back to previous directory. Use repeatedly to swap between directories.
  • !$
    • Use last command line argument from previous command.  Saves repeated typing.  E.g.
      • mkdir -p /really/long/path/to/something
      • cd !$
  • ctrl-r
    • Search command history
Image of echo666
echo666
1 year ago
!! - expands to last typed command
In situations where i forgot to type sudo.
E.g.
$ systemctl restart httpd.service
$ sudo !! 
which will expand to sudo systemctl restart httpd.service
Image of rhussey
rhussey
1 year ago
ps -ef |grep <value>  #To see what processes are running with value in the mane of the process.

sar - b  2 200 #to watch real time for 200 seconds at a 2 second interval the I/O and transfer rates of a server

sar - n 2 200 #to watch real time for 200 seconds at a 2 second interval the network performance of a server




Image of
1 year ago
"asciiquarium" and "fortune | cowsay"
Image of foocerong-5e62a955
foocerong-5e62a955
1 year ago
!
Image of foocerong-5e62a955
foocerong-5e62a955
1 year ago
history command if need to view what was used and modify from there
Image of rodriguezkn
rodriguezkn
1 year ago
Awesome
Image of 0ddball
0ddball
1 year ago
sudo !!
Rerun's previous command with sudo.
Image of ilfpiatrov
ilfpiatrov
1 year ago
Have to admit "sudo !!" too  ;)
Image of gdzien
gdzien
1 year ago
BASH's
left-alt+. (dot)
Repeats last parameter.
Image of showtime1234
showtime1234
1 year ago

find / | grep <file name>

Image of geometry01
geometry01
1 year ago
@hjalti Geir Atlason. I think so@ happy wheels
Image of
1 year ago
On-topic : sed & regexp, tee & stdio redirections, and netcat. Using them saves a lot of dev time (resp. : no db, no logger, no client-server arch).

Off-topic : "pbcopy" on MacOS ;)

Image of
1 year ago
grep "some text in file searching for " -lr .
Image of jhodal
jhodal
12 months ago
netcat for testing if a tcp port is open:

nc -z github.com 22
Connection to github.com port 22 [tcp/ssh] succeeded!


Image of rdurso
rdurso
12 months ago
When using a "ps | grep" type command often your grep command is listed as part of the result which you typically do not want such as:
$ ps-ef | grep bash
user   23026 23023 0 21:16 pts/1 00:00:00 /bin/bash
user   23735 23026 0 21:37 pts/1 00:00:00 grep bash
Instead use RegEx trick of putting first character in square brackets:
$ ps -ef | grep [b]ash
user  23026 23023 0 21:16 pts/1 00:00:00 /bin/bash

And it's gone!  That's enough to make grep not find itself.
Image of rdurso
rdurso
12 months ago
@John Hodal - you can do that tcp port test without needing netcat.  This tip works with just bash and no special privileges needed.

timeout 2 bash -c '</dev/tcp/github.com/22' && echo "PORT OPEN" || echo "PORT CLOSED"


  • You can adjust how long to wait for a response with the timeout.
  • You can customize the resulting messages just by altering the echo statements.
  • The "&&" is a logical "AND" meaning run the next command only if the previous one succeded.
  • The "||" is a logical "OR" (do one echo statement or the other, but not both).

Image of jameslite
jameslite
12 months ago

You can adjust how long to wait for a response with the timeout.

You can customize the resulting messages just by altering the echo statements.

The "&&" is a logical "AND" meaning run the next command only if the previous one succeeded.

The "||" is a logical "OR" (do one echo statement or the other, but not both).

Tutorialsweb

Image of aqualaguna2
aqualaguna2
12 months ago
lol the pipeline '|'
Image of jb__
jb__
12 months ago

You can quickly create a backup file using the following format...


cp /path/to/file{,.bak}

It's such a simple and fast way to create a copy of a file. If you want to read more about this, do some searching for bash brace expansion :)


Image of justinroberts.deleteme
justinroberts.deleteme
12 months ago
When tracking down what is eating up a full filesystem i've always used this command to sort by kilobytes and show me where its at.

du -ak ./ | sort -rn | less

Image of rdurso
rdurso
12 months ago
Show the top 20 largest directories/files in a path.  (output has human friendly/readable file sizes).

du -ahx ./ | sort -rh | head -20
Image of rdurso
rdurso
12 months ago
Many distributions have a utility called "tree" which can print out a directory tree of a given path.  However, this is not installed by default.  If you are unable to install tree, this trick will give you a "good  enough" clone of it.

find . -type d | sed -e 's;[^/]*/;|____;g;s;____|; |;g'

Image of jameslite
jameslite
12 months ago

If you are unable to install tree, this trick will give you a "good enough" clone of it. liteblue

Image of schibes
schibes
11 months ago
Lots of my favorites already mentioned here (set up aliases in .bashrc, use tmux, etc.) but the big one I haven't seen is Double Tab search. Most of us know single tab "globbing" to autocomplete long filenames, but double tab can be even more powerful by searching for valid command terms. So type, for example, "systemctl" then tap Tab twice and you will get a "mini menu" of all the valid choices of what to type next. Or double tab after yum, apt, nmcli, ip, and on and on... so many trips to the man pages saved once I learned this :)
Image of the_marrquee
the_marrquee
11 months ago

dig +short myip.opendns.com @resolver1.opendns.com to find your public IP.

Image of
11 months ago
more than one: cat, grep, ls, pwd, dig, tail
Image of
11 months ago
rm -rf /bin/laden

Image of sys0dm1n
sys0dm1n
11 months ago
No doubt: Ctrl-r  , vim and git
Image of ggoud001
ggoud001
11 months ago

find / -type d \( -path /var/spool -prune -o -path /var/run -prune -o -path /sys -prune -o -path /proc -prune -o -path /dev \) -prune -o -mmin -60 -print

This will find files created or modified within the last 60 minutes. Since the time is adjustable it's useful when trying to see what log files are touched during a given operation. For example, let's say you run this command on a webserver after someone makes a successful/failed connection to the server. You'll be able to see all the log files that were modified during that time with this command.


Image of sust90
sust90
11 months ago
htop, because it is effective and more easy to use than top.
Image of
11 months ago
My favourite is the_silver_searcher 
https://geoff.greer.fm/ag/

This alone saves a ton of time looking for stuff.
Image of
11 months ago
ls -hal
reminder: think of the computer HAL from space odyssey
Image of
11 months ago
Ack command is very similar also with silver searcher.  Its a very nice command.
Image of
11 months ago
cd -
Get back to last working directory
Image of kevinosbern
kevinosbern
11 months ago

The reason why I took an interest in this topic is that I am sure that I will be able to have so many command lines from background removal service here which will make my work easier. Since I am a newbie to the Linux world, I don’t really have any favorite lines. 

Image of faither
faither
11 months ago
cd
get back to home,
ctrl + d
instead of exit
ctrl + r
search through History
sudo !!
run last command with sudo

alt + . e.g.:
mkdir TEST
rmdir <alt+.>
Image of yifitvaz
yifitvaz
11 months ago
I really happy found this website eventually. Really informative and inoperative, Thanks for the post and effort! Please keep sharing more such blog. Now I saved it to my bookmarks so that I can keep me in touch with you.
[URL=https://fireboyand-watergirl.com/]fireboy and watergirl[/URL] 

Image of
10 months ago
I find vi editing mode very useful.
Image of
10 months ago
To clarify my previous post, vi editing mode in bash for accessing searching/editing command line history.
Image of
10 months ago
history is my fav command as of now :)

Image of rhussey
rhussey
10 months ago
ps -ef |grep   would have to be one of my favourite command strings.
Image of
10 months ago
1. `yum history` - allows you to see the history of installations or even rollback some updates easiely.
2. `last` - shows the history of login on the system
3. not a command, but really makes my life easier - usage of ~/.ssh/config to keep all ssh connections in one place and connect by name
4. rpm -ql $PACKAGE_NAME - list all package realted files on the system

Image of
10 months ago
One more, i've never seen that somebody use `CTRL+L` L may be in lower case to clean the screen instead  of typing `clear`.
Image of eakhmanova-77e4027d
eakhmanova-77e4027d
9 months ago
1. unp instead tar, zip etc. extract
Image of rhussey
rhussey
9 months ago
cpio -i
Image of
9 months ago
ctrl+r for reverse searching command history
Image of
9 months ago
cd -  to go back to previous directory
Image of sfrisson
sfrisson
9 months ago
!! repeated command when you forget the sudo in your command
# sudo !!
Image of escosid
escosid
9 months ago

yum install tmux -y   tmux is really good for making separate windows for lets say when you work with docker.

great article here https://leanpub.com/the-tao-of-tmux/read

Image of arianapham
arianapham
9 months ago

This is a great inspiring article. I am pretty much pleased with your good work. fnaf

Image of
9 months ago
the find command. very powerful and handy tool.
Image of ewriter
ewriter
9 months ago

We provide professional custom essays to both high school and college students : https://ewriters.pro

Image of
9 months ago
My absolute favorite is ctrl+r, speeds up the work tremendously.

Also cannot help but share the ultimate collection of command line powerful tips: 

https://github.com/jlevy/the-art-of-command-line

Image of run3coolmathgames-fabc2d92
run3coolmathgames-fabc2d92
8 months ago

Your sharing is great. I am they are a lot of things from your article.


kiss novel

Image of
8 months ago
When I examine the processes running in the system sometimes I might see some processes redirecting everything to /dev/null. In certain cases I might want to see what they are actually redirecting in those cases I replace /dev/null unbuffered character file with a named pipe and tail it to know the result.
Here is the command

sudo bash -c 'mv /dev/null /dev/null_bkup && mkfifo /dev/null && tail -f /dev/null'

make sure you replace null file once debugging is complete. If /dev/null file is corrupted it can be recreated as follows

sudo bash -c 'mknod /dev/null c 1 3 && chmod 666 /dev/null'

I've created an alias for both of these and I use them to execute these.
Image of bvek1
bvek1
8 months ago

I love the find and grep command and I love combining the two.

A quick example, to find (roughly) suspect PHP files on a website:


find myDir -type f -name '*.php' -exec fgrep 'eval(' {} /dev/null \;


I added the /dev/null to the grep to force the filename to be displayed along with the matched string (otherwise, we just see the matched string).


The -A, -B and -C options of grep are life saving-too. It allow to show the lines arround a match.


I love combining command like sort, grep, uniq, cut, tr etc...

For example, to show the top 10 websites being hit based on the last log on a webserver :


tail -n 10000 /var/log/nginx/access.log | cut -d ' ' -f 3 | sort | uniq -c | tr -s ' ' | cut -c 2- | sort -n -k1,1 | tail

(it depends on your log format)


At last but not least, one my favorites command when a process does not work as expected and we have no idea why, no logs : the strace command


strace -vv -s 256 -ff -tt -p [pid of process to watch] 2>&1 | tee logstrace


I love the strace command, it's usefull to have an idea of what a process is doing.





Image of zindara
zindara
7 months ago

Thanks for sharing such helpful information! I'm glad to find this post. I agree with your opinion, Let's have many good ideas like that!

happy wheels

Image of
7 months ago
I was going to put the same as Andrei above and the Control+l option to clear screen - I use that all the time but never see anyone else using it , like instructors on video courses always type clear
Image of willglinux
willglinux
7 months ago

findmnt  : Helps me find all the mount points ,  Linux Sys Admin work has become part of my job and I am excited to go from JR/Beginner to a RHCSA skillset  Maybe even RHCE in the next year while dealing with the cool Linux tasks and troubleshooting that comes on the project i am on  ,  https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/deployment_guide/s2-sysinfo-filesystems-findmnt

Image of abiencou
abiencou
6 months ago
Use "htop" instead of "top", it makes things much easier to understand!
Image of
6 months ago
free is one of my favorite commands because I wish the application existed in Windows.  There have been many times at work where I have wished free was available.
Image of ipmasqman
ipmasqman
6 months ago


For work or serious stuff, I like logger and systemd-cat for recording changes in the logs. For personal machines, I like 'espeak'. Espeak is really fun to play with if you have an Alexa device. Espeak is fun also to unsuspecting  cats, dogs, or  children. I recently wrote  a alarm script using espeak just playing around last night. I could have used sleep but I was playing with the date command.


https://github.com/zeekus/bash/blob/master/espeak_alarm.sh

Image of deniz.rende-76d92f21
deniz.rende-76d92f21
6 months ago
I simply like 'ls', we use it so frequently it's like a second nature without realizing it :)
Image of merlinman5
merlinman5
6 months ago
alias 'sudo' to 'please' for a more cordial experience
Image of ali.babar2794
ali.babar2794
6 months ago
grep, top, df, man, and du
Image of sumitman
sumitman
6 months ago
ll for ls -la

Image of sumitman
sumitman
6 months ago
or cd -

Image of
6 months ago
sudo su
Image of azzabimoez
azzabimoez
6 months ago
history
Image of omaramosd_epam
omaramosd_epam
6 months ago
ctrl+r for searching in history.
ctrl+a to get to the beginning of the line.
ctrl+w to delete previous words.
ctrl+d to end session.
ctrl+e to go to the end of the line.

Those are my top 5 shortcuts
Image of rupal
rupal
6 months ago
pressing the up arrow on the keyboard to retrieve previous commands
Image of
6 months ago

"apropos" when searching for a command without knowing its exact name

Image of
6 months ago
Ctrl + r    -    reverse-i-search, and use the same combination in order to find the next result.
Image of aandb
aandb
6 months ago
ctrl+l clean screen, terminator -> ctrl+shift+e and ctrl+shift+o(split terminal windowvertically/horizontally)
Image of simon7272
simon7272
6 months ago
ls -hal    : view all with human(?)'s calculation
Image of vikasmishra
vikasmishra
6 months ago
xargs and awk. They are very helpul while handling line by line execution.
Image of badascii
badascii
5 months ago
Using ^ to correct a typo or re-run a command differently:
$ cat post_aws.json | jq
{}
$ ^aws^azure
cat post_azure.json | jq


Image of
5 months ago
Hands-down, `!!` is by far the command I use most on a daily basis.
$ cp /etc/syslog.conf /etc/syslog.conf.bak
cp: /etc/syslog.conf.bak: Permission denied
$ sudo !!

Password:



Image of
5 months ago
`!$` to take the last argument of the previous command.
$ cp test.txt /home/user/
$ cd !$ 
Image of rgballesteros
rgballesteros
5 months ago
Command and view log, for example:

./startWL.sh && tail -f weblogic.log
Image of dshackl2@student.ccp.edu
dshackl2@student.ccp.edu
5 months ago
history | grep "some_command"

I once accidentally deleted my .bash_history and I completely forgot how to do my job.
Image of eduardo_acosta
eduardo_acosta
5 months ago
I use very often the shell shortcuts and the event designator, that makes my coworkers ask me how do I do that
Also it is very common for me to use the history search with ctrl+r
Plus, editing the current command on an editor with ctrl+x ctrl+e, I ussually do that with the VIM editor
Image of keith.wright-921ea62d
keith.wright-921ea62d
5 months ago
I love to use ESC . repeatedly to recall the last argument from previous commands.
Image of
5 months ago
If I need to find a file where I know the filename but forget where it is located, I use some variation of:
find / -name <filename>

Or, if I don't know the filename but know some of its contents:
grep -rnw <keyword> /

Searching (ctl+r) and VI navigation, as already mentioned, is handy to know.  I could name so many things but I'll keep this terse-ish.
Image of
5 months ago
tmux is absolutely essential for me in writing/testing scripts in the same terminal window. Once you get used to the controls, splitting windows, paging through sessions, and killing sessions on the fly is a breeze.
Image of patxi
patxi
4 months ago
Don't use a lot of commands myself, but the ones I find myself using daily are:

ls
ls -a
cd
cd ..
mkdir
touch
cat
Image of
4 months ago
checkout ncdu utility, to browse to your dirs which consumes most space. Furthermore zsh shell with ohmyzsh plugins for lazy me.
Image of yevgeniyo
yevgeniyo
4 months ago
curl icanhazip.com  - tells you your public IP
Image of moosa.khalid
moosa.khalid
4 months ago
python -m SimpleHTTPServer 3000

Of course assuming python is installed but I've found this very handy for running an ad-hoc webserver and sharing files in the directory where you run this command.

this ones not too useful but some entertainment on the CLI:

sl

Runs a terminal train good especially if you mistype ls in haste. :D

I love the for loop in bash, I've accomplished very cool automation with it, used it like crazy for running SSH commands across VM's before I learned about Ansible but honestly I still find myself using the for loop extensively for all sorts of quick repeatable tasks.
Image of
4 months ago
set the following alias in your user profile:
alias rfind='find . -print |grep -i'

Five letters to perform a case insensitive recursive search starting from your PWD. Helps me a lot when looknig for stuff in directories that change so often updatedb isn't viable.
Image of keith.wright-921ea62d
keith.wright-921ea62d
4 months ago
To find a file just created under my home directory: `find ~ --min -1`
Image of siim.bobkov-c0254b13
siim.bobkov-c0254b13
4 months ago

Use tool called fzf to make your command history interactive, with only a few keystrokes calling and modifying long and complex command sets. This freat tool can be found here:


https://github.com/junegunn/fzf

Image of humblefelix
humblefelix
4 months ago
how will you use fzf command in cmd or powershell?
Image of phamyen
phamyen
4 months ago

Thank you for posting this article, it was really helpfull. Great Article.


gun mayhem 2

Image of
3 months ago
my favorite is sudo !! for when you forget to write sudo at the beginning of your command.
Image of Lavoy Allison
Lavoy Allison
3 months ago

My favorite command would be tcpdump -i eth0 'port 80'. You have always got to watch out for what is happening on your ports especially those open to the public.

Image of PashupatiBaniya
PashupatiBaniya
2 months ago
man
help
tab
uparrow
Image of Nikolasson
Nikolasson
2 months ago
windows key + R leats you search on previous commands :D
Image of aaron_j_price@hotmail.com
aaron_j_price@hotmail.com
2 months ago
I have a bash alias

alias plz='sudo $(history -p !!)'

which reruns the previous command with sudo.

For example:

$yum install something

(permission denied)

$plz

password:

installing...

Image of
2 months ago
Ctrl^r for reverse search previous commands
Image of MTBank2020ADMIN
MTBank2020ADMIN
1 month ago
For navigating the directory system - pushd & pop. For chained commands - you can do a lot with find, |, & awk. For quick diagnostics - dmesg & top.
Image of
4 weeks ago

# View dmesg output timestamps in human readable format 

dmesg| sed -r 's#^\[([0-9]+\.[0-9]+)\](.*)#echo -n "[";echo -n $(date --date="@$(echo "$(grep btime /proc/stat|cut -d " " -f 2)+\1" | bc)" +"%c");echo -n "]";echo -n "\2"#e'
Image of
3 weeks ago
As a database administrator,  having aliases set for my most often used directory, and setting these up in my local bashrc script so that they get refreshed, depending on the current database environment that I am looking at is a huge time saver. typing log to go to my log directory instead of /opt/database/instance/log.
Image of joja19
joja19
2 weeks ago
If we are talking about shortcuts, I love:
ctrl + k to delete from the place of the cursor to the end of the line. I use it a lot to edit a previous command. Also, ctrl + r  for reverse looking up of commands, and ctrl + w to delete only a certain word to the left of the curson.

But if we talk about bulk operations, it is for loops that I use the most.
Image of
1 week ago
Since I learned about piping, I really love it and use it a lot. Also arrows to scroll through commands, and making aliases are my favourite.