This article will be beginner friendly, only this time in the Linux console. The material is presented, in my experience, from the most frequently used to the rarest. As in the previous article about Nginx tips and tricks, I lacked these hints and tricks at the beginning of my career.
Safety
Slightly less than all the malware that lives on the global network is designed for Windows and its ecosystem. Linux will protect your local systems and networks from infections like trojans, viruses, miners, lockers, and adware.
Availability
You can get a legal (licensed) copy of the system free of charge by downloading it from the Internet. Yes, there are commercial distributions like RHEL, but you pay for updates and technical support in them. Again, these distributions can be legally downloaded without paying a dime. An enterprise or organization can save a lot on licenses because pirated software is extremely risky and unacceptable. In my opinion, it is also better for an ordinary home user not to use pirated (hacked) programs, even despite the almost zero risk of falling under the article. After all, a hacked system or program can be unstable. And what's stopping pirate hackers from putting some kind of trojan or adware into the code?
Transparency
Linux and most of the software in its ecosystem have open/free licenses like GPL and BSD. This means that the source codes of programs are not stored somewhere in the deep programmer mines of corporations but lie before the eyes of the whole world on public servers. Moreover, the development process of this software is also completely open, every change is fixed and visible to everyone. Therefore, the code is constantly checked by a decentralized network of experts worldwide for errors, vulnerabilities, and malware. If anyone can send changes (patches), such software improves faster than proprietary software (adjusted for popularity and development model, of course).
Linux is also more commonly used as a server operating system. For example, here is a comparison of using Linux and Windows.
1. Return to the home directory
You can use the command below to change your home directory from anywhere on the Linux command line:
cd ~
You can also use just cd to return to your home directory:
cd
Most modern Linux distributions have a shell preconfigured for this command. This will save you a few keystrokes.
2. Use Tab to autocomplete
One of the main Linux command line tips is to use Tab to autocomplete. Using the tab key is probably the most obvious trick but somehow remains ignored. Many people know about it, but few people use it in practice. After typing something in the Linux terminal, users can press the tab key to get suggestions for all possible options, starting with the string they typed.
For example, if you try to change to the random_folder_123
directory, you should only type cd r
. Then you can click on "Tab" to see all the possible options. In addition, if there is only one such option, it will automatically be substituted into your command line.
3. Which
The which
command prints the full path to shell commands. If it cannot recognize the given command, it will throw an error.
4. Running multiple commands in one command
Suppose you need to execute several commands one after the other. Are you waiting for the first command to complete and then running the next one?
You can use the ";" separator for this. This way, you can run multiple commands on the same line:
command_1; command_2; command_3
5. Run multiple commands in one command only if the previous command was successful
In the previous tip, you saw how to run multiple commands on the same line to save time. But what if you need to make sure the commands work correctly?
For example, do you want to build the code and then, if the build was successful, run make?
You can use the &&
delimiter for this case. The &&
ensures that the following command will only be executed when the previous command was successful:
command_1 && command_2
Also, a good example of this command is when you use sudo apt update && sudo apt upgrade
to upgrade your system.
6. Search and use commands you have already used
Imagine a situation where you used a long command a couple of minutes/hours ago, and you have to use it again. The problem is that you can't remember the exact command anymore.
A reverse search will save you. You can search the history of a team using a search term.
Just use the ctrl + r
keys to launching a reverse search and type in some part of the command. It will look into the history and show you the commands that match the search query:
ctrl+r search_term
By default, it will only show one result. To see more results that match your search term, you will have to use ctrl + r
it repeatedly. To exit reverse lookup, just use Ctrl+C
.
Or
Using History to Access Frequently Used Commands
You may have many commands that you use frequently. But it is often very difficult to remember the exact command with all the parameters. You can solve this problem with Linux command line tricks. Use the following example to get a command from history:
history | grep ufw
It may be worth keeping some environment variables, such as HISTSIZE, large to determine the capacity of the history store on a Linux machine. As a result, you can easily save a significant amount of time and effort. You will not need to access the Internet so often to remember how to write the desired command.
In most Linux terminals, you can also scroll through the commands from the history with the arrows on the keyboard, this is very convenient.
7. Unfreeze your Linux terminal from accidentally pressing Ctrl+S
You are probably used to using Ctrl + S
to save. But if you use this in a Linux terminal, you will have a frozen terminal.
Don't worry, you don't need to close the terminal anymore. Just use Ctrl + Q
and you can use the terminal again.
8. Use the help command to learn more about other commands
The last, and perhaps most important, addition to this list of useful Linux command line tricks comes down to constantly learning new commands. All commands in Linux have detailed help and can be invoked with the --help
argument. Look there more often to clarify nuances or arguments for an unknown command. Also, don't forget the man pages:
ufw --help
9. Jump to the beginning or end of a line
Suppose you are typing a long command, and halfway through, you realize that you need to change something at the beginning. You would use multiple left arrow clicks to move to the beginning of the line. And the same goes for going to the end of the line.
Of course, you can use the Home and End keys, but alternatively, you can use Ctrl + A
to go to the beginning of the line and Ctrl + E
to go to the end.
10. Read log file in real-time
In situations where you need to parse logs while the application is running, you can use the tail command with the -f option:
tail -f path_to_Log_file
You can also use the normal grep options to display only the lines that matter to you:
tail -f path_to_log_file | grep search_term
You can also use the F option here. Thus, if the log file is created again, the tail
will continue logging.
11. Terminate a command or process that is currently running
One of the best Linux command line tricks to kill a running command or process is to use Ctrl+C
. If you want to stop a command running in the foreground, you can use this keyboard shortcut effectively. It works in all terminals known to me.
12. Copy and Paste
While "copy and paste" is one of the most common computing tasks, there are many confusing combinations for various Linux distributions and terminal applications. Therefore, programmers must know reliable Linux command line tricks for copying and pasting commands using keyboard shortcuts.
Finally, you can use the keyboard shortcuts Ctrl+Shift+C
to copy the command and then use Ctrl+Shift+V
to paste the command. Unfortunately, different terminals have their own confusing combinations, which often differ for such a simple task. Therefore, it is worth remembering the necessary key combinations for the terminal that you often use.
13. Reusing the last argument from a previous command
The argument of the previous command is always useful in various situations. For example, if you just created a directory and want to visit it:
mkdir /tmp/folder_long_name/
and use the previous argument:
cd !$
14. Reading a file using without opening it completely
If you want to view the contents of a text file, cat
might seem like the best solution. However, the cat command will display the shared file on the screen. You might also consider using Vi, Vim, and other text editors with a terminal to read the file. For example, I like mcedit
.
However, all of these utilities can get very bogged down on really large files. Log files of some programs, such as Apache, can be hundreds of megabytes and even gigabytes. It will be very difficult to view or output to the console such a file. For such purposes in Linux, you can use less
. This utility displays the file page by page, no matter its size. Another option to (only) view such large files is to use tail
the exact location in the file.
For example, if we only want to see the last 100 lines in the log file, the command would look like this:
tail -f -c 100 path_to_Log
To see the contents of a file cat
is not the best option, especially if it's a very large file. The cat
command will display the entire file on your screen.
You can use Vi
, Vim
, or other terminal-based text editors, but if you just want to read a file, the less
command is a much better choice:
less path_to_file
15. Reading compressed logs without extracting
Server logs are usually gzipped to save disk space. This poses a problem for a developer or system administrator parsing logs. You may need to copy it to a local directory and then extract it to access the files because sometimes there is no written permission to extract the logs.
Luckily, the z
commands are a lifesaver in these situations. The z
commands provide alternatives to the usual commands you use to work with log files, such as less
, cat
, grep
, etc.
This way, you get zless
, zcat
, zgrep
, etc., and you don't have to extract the compressed files explicitly.
It was one of the secret finds, thanks to which a colleague treated me to coffee.
16. Reuse the previous command in a new command with !!
You can call all the previous commands with !!
. This is especially useful when you need to run a command and realize that it needs root privileges.
This can save time when you try to run a command that lacked privilege and now needs to be re-executed with sudo privileges, just type:
sudo !!
17. Using an alias to fix typos
You probably already know what the Linux alias command is. With their help, you can correct your own frequent typos.
For example, you can often mistype grep
as gerp
.
If you add an alias to your bashrc
like this:
alias gerp=grep
Now, you don't have to enter the command again.
An example of useful aliases:
# clear console
alias c='clear'
## get rid of command not found ##
alias cd..='cd ..'
## a quick way to get out of current directory ##
alias ..='cd ..'
alias ...='cd ../../../'
alias ....='cd ../../../../'
alias .....='cd ../../../../'
alias .4='cd ../../../../'
alias .5='cd ../../../../..'
## Colorize the grep command output for ease of use (good for log files)##
alias grep='grep --color=auto'
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias h='history'
alias now='date +"%T"'
alias nowtime=now
#show open ports
alias ports='netstat -tulanp'
# install with apt-get
alias apt-get="sudo apt-get"
# become root #
alias root='sudo -i'
alias su='sudo -i'
## pass options to free ##
alias meminfo='free -m -l -t'
## get top process eating memory
alias psmem='ps auxf | sort -nr -k 4'
alias psmem10='ps auxf | sort -nr -k 4 | head -10'
## get top process eating cpu ##
alias pscpu='ps auxf | sort -nr -k 3'
alias pscpu10='ps auxf | sort -nr -k 3 | head -10'
## Get server cpu info ##
alias cpuinfo='lscpu'
## set some other defaults ##
alias df='df -H'
alias du='du -ch'
# top is atop, just like vi is vim
alias top='atop'
These are just recommendations from me, you'd better add something that you use most often
Here is a surprisingly useful tool that executes a misspelled command when writing the wordfuck
after a misspelled command -
18. Using the yes command for commands or scripts that require an interactive response
If there are some commands or scripts that require user interaction and you know that you need to type Y
every time input is required, you can use the YES
command.
Just use it like this:
yes | command_or_script
19. Clear the file without deleting it
If you just want to clear the contents of a text file without deleting the file itself, you can use a command like this:
> filename
20. Find if there are files containing specific text
There are several ways to search on the Linux command line. But in case you just want to see if there are files containing certain text, you can use this command:
grep -Pri Search_Term path_to_directory
Or is it better to use find
. A good example of finding files:
find /home/user -type f sensetive_data.txt
This command will search for all files located in /home/user
. The find command is extremely powerful, and you can pass additional options to make your search even more detailed. If you want to find files larger than a given size, you can use:
find. -type f -size 100M
The above command will search the current directory for all files larger than 100MB
. Do not run the command from the root directory of your Linux system, as this may result in a lot of I/O
on your computer.
For example, suppose we want to find all files in a directory and change their permissions. This can be easily done with:
find /home/user/sensetive_files/ -type f -exec chmod 644 {} \;
21. pwd
Prints the current directory to the screen. This can be useful if your Linux command line does not display this information. This command will be required in Bash programming, where a script is executed to get a link to a directory.
22. View the size of a file or folder
To find out the weight of a directory or file, simply type:
du -sh file_path
23. View disk space
To understand how much space is left on which disk, enter:
df-h
24. Repeating a command until it successfully completes
To run a command until it completes successfully use the command's return code in this construct:
while! [command]; do sleep 1; done
For example:
$ while ! ./run.sh; do sleep 1; done
cat: run.sh: No such file or directory
cat: run.sh: No such file or directory
hackernoon.com
The command in this example will be repeated until the run.sh
file is found and its contents are displayed on the screen.
Be careful with this.
25. Table output
Calling the ls command, or anything else that prints data to the screen, can lead to long lists that require a lot of scrolling to see. What is displayed on the screen can easily be arranged as a table using the column -t command. For example:
cat /etc/passwd | column -t
26. Cleaning the Console
The clear command clears the terminal screen. The keyboard shortcut Ctrl + L
allows you to achieve the same thing faster.
27. Create directory trees with a single command
You probably know that you can create new directories with the mkdir
command. So, if you want to create a new folder, you will run something like this:
mkdir folder_name
But what if you want to create five subfolders in that folder? Running mkdir
Five times in a row is not the best solution. Instead, you can use the -p option like this:
mkdir -p new_folder/{folder_1,folder_2,folder_3,folder_4,folder_5}
28. Authenticate to SSH Without a Password
If you log into a particular SSH server frequently, having to enter your password each time can be annoying. You can skip it if your host and server exchange certificates.
First, you must create it. Run the ssh-keygen
command. This creates a private/public key pair and stores it in ~/.ssh/id_rsa
. Now, you need to copy the public key to the server using this command: ssh-copy-id [email protected]_host
. You will be prompted for the password for the server, and the public key will be copied. Now you can log in to this server without a password from this particular system.
Note: This method is by no means less secure than basic authentication. It may even be more secure if your local system is secure. If you don't compromise the private key, you won't be able to log in to SSH.
29. Keep Your Program Running in the Background
If you run the program in a terminal, it will be killed as soon as you end your terminal session. To prevent this and keep the program running, use the nohup
command - it means "don't hang".
For example, to transfer files to and from the server using scp
and be sure that the transfer will continue even if you accidentally close the terminal window, use this command:
nohup scp very-big-file.mkv [email protected]:~/very-big-file.mkv
nohup
also creates a file called nohup.out
to store the output of the command.
30. Password Protect Files in VIM
If you are one of those who use Vim
, I admire you. You'll be pleased to know that you can password-protect files in Vim
using the vim +X
filename command, or the :X
command directly in Vim
.
31. List Users
If you have privacy concerns, you can check who is logged in at any time. You can use the w
command to list all users currently logged into the system. What's more, you can write a script that will run this command on a schedule and send you an email if something goes wrong.
32. Ping
If you want to check if your system is connected to a router or the Internet, the PING
(Packet INternet Groper) the command will do. It uses the ICMP protocol to connect to other devices.
There are several options to use with the ping command, ping
displays address as a hostname, so if you want to see them in numbers, use the ping -n
command; ping -i
to specify the interval between transmissions, as the default is 1 second.
33. Sorting by Processes by (Memory - CPU) Usage
On Linux, you can list all current processes and sort them by the amount of memory consumed by each process using the ps aux
command.
This command can be useful in situations where your system is using more memory than usual. Using the ps aux
command without additional options will only display the current processes running on your system.
To sort this list of processes by memory usage, we can use the sort command along with the -nk
option, concatenating both commands together:
ps aux | sort -nk 4
As the title of this section of the article suggests, we can also use the ps helper command associated with the sort command and the -nk
option to sort the listed processes by CPU usage:
ps aux | sort -nk 3
34. Monitoring Command Outputs
We can use the watch command to monitor the output of a command by periodically running that command at a certain set interval of time. A great example of how we can use the watch command is the date command.
Using the below syntax on the Linux command line will cause the watch command to run the date command every 2 seconds, and the result will be displayed in your terminal.
This is useful for running the date command continuously without typing it repeatedly.
For example, let's run a command with a “super dynamically” changing output:
watch date
35. htop
Once htop
is installed, you can run it by typing htop
on the command line. When you do this, you'll get a complete overview of all processes running on your system, along with details such as process IDs, CPU and RAM usage, and how long they've been running.
Of course, we all know this command but htop
is quite a powerful tool. Also, their site looks good with old-school colors.
Last tip/trick as a bonus
bc
is another interesting and useful command for Linux users as it allows you to enable the command line calculator in the Linux terminal when you run the following command;whatis
- If you want to know what a particular Linux command can be used for, just type whatis <command name>
in a terminal shell, showing you a short one-line description of that particular Linux command;who
- This is for system administrators who manage the various users on a Linux system. The who
command, when executed in the Terminal, shows a complete list of users currently logged into the Linux system.free
- The free command can be used to check how much memory is free and used in both physical and RAM memory on the system. There are also a few options to use with the free
command. For example, you can use free -b
to view results in bytes, free -k
to display available and used memory in kilobytes, free -m
to view in megabytes, free -g
to view results in gigabytes and free –tera
to view results in terabytes.sl
is a completely useless command. I've always liked animation with symbols. This is a steam engine running through the terminal window. Nothing special. You can also try aafire
. Installation may be required. Or Linux can spawn an amazing cow that can talk to you. For example, to say, “In what despair are you, since you turned to me?” use:
echo "In what despair are you, since you turned to me?" | cowsay
Output:
While working with the console, everyone can accumulate their own experience of the most used commands, their own tricks, and cheats. Each experience is unique and interesting.
If I missed something, but I definitely missed it, you can add me in the comments.