Bash – the most widely used command interpreter in UNIX-like systems, provides the ability to perform almost any action through the terminal. Not all operations can be carried out through a graphical interface, whereas Bash offers the opportunity for complete control over the system.
Familiarizing oneself with Bash commands becomes crucial in everyday work, as many tasks are more efficiently and quickly executed through Bash commands in the terminal. For instance, searching for files based on content, modifying files, copying and moving them, and so on. In the absence of a graphical interface, Bash becomes a key tool for server management. This is especially relevant in the case of remote servers where a graphical interface is not installed.
The goal of this article is to introduce users to Bash, explore the fundamental commands that developers use in their daily work.
Obtaining information about a command
To invoke various programs or commands, it is often necessary to use various flags, which can be challenging to remember. It is convenient to immediately refer to manuals in the terminal, providing detailed descriptions of the command syntax, options, parameters, and possible usage scenarios. To access information in the terminal and formulate a query that matches the required task, you can use:
- man – short for “manual.” Execute man when you need a guide to various programs and utilities in UNIX-like operating systems. For example, the command ‘man ps’ will display a detailed manual on how to use the ps command. In this manual, you will find information about the command syntax, parameters, environment variables, and other important aspects of working with the command line. You can use man to get help on almost any command or program in your system. Exit the manual: press the Q key.
- The –help flag is a common standard in the command line for obtaining reference information about a program or command. When you add –help to the execution of a command, the program usually outputs a brief overview, explaining the main options and functionality of the command. For example, ‘grep –help’ will display information on how to use the grep command. The –help flag primarily provides information on command usage (flags, variables, etc.), and it is more convenient to use it as a quick reference, whereas man provides comprehensive information about the program.”
Working with processes:
ps – used to display current processes.
Example:
Displaying all processes running on the system: PS AUX
Displaying all processes on the system with a name filter (simply create a name template): ps aux | grep -i '*process_name*'
. We’ll delve into grep further.
top – in operating systems, provides an interactive and dynamic view of system load and running processes.
kill – used to terminate a process.
Example:
Terminate a process by ID (you can find the ID with the command ps
): kill PID
.
Terminate a process by process name: pkill process_name
.
df – used in operating systems, provides information about available disk space.
du – used to get sizes of files and directories in the current directory, making the output more human-readable by converting sizes to kilobytes, megabytes, gigabytes, etc.: du -h /path/to/directory
.
Most commonly used options:
- -s or –summarize: shows the total size of the directory.
- -c or –total: shows the total size of multiple directories.
- -k, -m, -g: change units to kilobytes, megabytes, and gigabytes, respectively.
Based on the du
command, you can create a more complex command using other utilities to find the heaviest files in a directory:
Find the top 5 heaviest files: du -ahx . | sort -rh | head -5
.
File System Operations:
ls – used to view the contents of a directory. Typically, the command is used with the flags -lah to display hidden files (those starting with a dot) and provide more information about the files (their size, last modification date, access permissions). The ls
command has numerous options to customize the output according to your needs. For more detailed information on available options, you can use the man
command or ls --help
. Example of usage: ls -lah
pwd – used to display the full path of the current working directory. The pwd
command is useful when you need to know which directory you are in, especially when writing scripts or commands in the terminal.
cd – used for navigation in the terminal through directories, to change the current working directory in the command line.
Basic usage examples:
Absolute path: cd /home/user/Documents/work/project
Relative path: cd Documents/work/project
Navigate one directory up: cd ..
Go to the home directory: cd
Go to the previous directory: cd -
Navigate to a directory starting from the home directory (without specifying the full path): cd ~/Documents/work/project
mkdir – used to create new directories.
Examples of usage:
Create a new directory in the current one: mkdir directory_name
Create multiple directories at once: mkdir dir1 dir2 dir3
Create nested directories: mkdir -p path/to/nested/directory
The -p
flag allows creating nested directories. In this case, the directory structure path/to/nested/directory
will be created, and all intermediate directories will be created automatically if they do not exist.
Create a directory and set access permissions: mkdir -m 755 new_directory
touch – allows creating files and editing file timestamps from the terminal. It is often used to create a new empty file through the command line. If needed, I usually use Vim to write data directly to the file; otherwise, Vim won’t create an empty file. We’ll cover the Vim command further.
Usage examples:
Create a file: touch filename.txt
If the file filename.txt
already exists, the touch
command will update its timestamps without affecting the file’s content.
Create multiple files at once: touch file1.txt file2.txt file3.txt
Create a file using an absolute path: touch /path/to/newfile.txt
cp – the command is used to copy files and directories.
Examples:
The command cp from.txt to.txt
copies the contents of the file from.txt
to the file to.txt
. If the file to.txt
does not exist, this utility will create it.
Copy the file source_file.txt
to the directory destination
: cp source_file.txt destination/
Copy multiple files to the directory directory
: cp file1.txt file2.txt directory/
Copy a file with a name change: cp file.txt directory/new_name.txt
Copy a directory: cp -r source_directory/ destination/
Copy with confirmation (prompt before overwriting): cp -i source_file.txt destination/
The -i
flag requests confirmation if a file with the same name already exists in the target directory.
mv – a command in the terminal used to move files and directories. This command is also often used for renaming files.
Move a file to another directory: mv text.txt /path/new-dir/
Rename a file: mv old-file.txt new-file.txt
Move all files from one directory to another: mv /path/dir/* /path/new-dir/
Move a file to the current directory (using .
): mv /path/dir/file.txt .
Move multiple files to a directory: mv file-1.txt file-2.txt /path/dir/
Interactive move with confirmation: mv -i file.txt /path/new-dir/
The -i
flag requests confirmation if a file with the same name already exists in the target directory.
rm – for deleting files; to delete directories with files inside, the -r
flag must be used.
This command does not move files or directories to the trash, making their recovery impossible. Therefore, be cautious when using this magic!
Deletion with confirmation: rm -i file.txt
Delete files using patterns: rm *.txt
Delete multiple files: rm file-1.txt file-2.txt
Important! When using thecp
andmv
commands, if you use an existing file as the second argument, it will overwrite the file from the first argument, and it will be impossible to recover it!
Example: Let’s say we have two files, file1.txt
and file2.txt
. We execute the command
mv file1.txt file2.txt
As a result, file1.txt
becomes file2.txt
, and the data from the original file2.txt
is overwritten, making it impossible to recover.
To avoid such behavior, you can use the -i
flag. In this case, a warning will be issued that the selected file will be written over the existing one in the destination directory. You will have the option to cancel this action by typing n
and pressing Enter.
mv -i file1.txt file2.txt
Example: Let’s say we have two files, file1.txt
and file2.txt
. We execute the command
mv file1.txt file2.txt
As a result, file1.txt
becomes file2.txt
, and the data from the original file2.txt
is overwritten, making it impossible to recover.
To avoid such behavior, you can use the -i
flag. In this case, a warning will be issued that the selected file will be written over the existing one in the destination directory. You will have the option to cancel this action by typing n
and pressing Enter.
Pro Tip:
To avoid unpleasant consequences, it’s very convenient to set up aliases once:
alias mv="mv -i"
alias cp="cp -i"
alias rm="rm -i"
We will explore the concept of aliases in the next article.
find – used to search for files and directories in the file system based on various criteria.
Basic syntax (simplest form, the command can be customized very flexibly using flags):
find `where to search` -name `file name, can use a pattern`
Examples:
Search for a file by name:
find ./ -name "file"
Search for files by extension:
find /abs/path/dir -name "*.js"
Search for files by size:
find ./dir/ -mtime -7
You can specify the maximum depth (if you want to search only in your folder or limit it to a few levels of nesting): -maxdepth 2
Combining multiple conditions:
find /path -name "*.extension" -size +1M
File Operations:
cat – concatenation, often used to display the contents of files on the terminal screen.
Examples:
Display the contents of a file on the screen:
cat file.txt
Concatenate the contents of files:
cat file-1.txt file-2.txt
Display all files in a directory:
cat *
Display all files in a directory with the extension .js
(you can use any pattern):
cat *.js
Number lines when displaying a file:
cat -n file-1.txt
grep – a utility used for searching text in files or the output of other commands. You can specify the text to be searched using regex.
Example:
grep -E -i '^(linux|unix)' file-name.txt
The -E
flag is used for regex, and the -i
flag is for case insensitivity.
Simple text search in a file:
grep "searched_text" file.txt
Search for text in multiple files:
grep "searched_text" file-1.txt file-2.txt
Recursive search in a directory:
grep -r "searched_text" ./dir/
Highlighting matches:
grep --color=auto "searched_text" file.txt
Exclude lines with matches:
grep -v "searched_text" file.txt
Find a line matching the regex ‘^(linux|unix)’ in the current directory (recursively going through all files), including the file and line in the output:
grep '^(linux|unix)' -insr ./
grep
is a very useful utility, especially when working with application logs on a server.
head – used to view the first few lines of any text file.
Example:
head -30 file.txt
Displays the first 30 lines of the file file.txt
.
tail – similar to head
, but instead of showing the first lines, it shows the last n lines of a text file.
Example:
tail -100 file.txt
Displays the last 100 lines of the file file.txt
.
diff – compares the contents of two files line by line. After analyzing the files, it will display the lines that do not match.
Example:
diff file1.txt file2.txt
vim – a text editor in UNIX-like systems that provides extensive capabilities for editing text files. Basic commands and concepts related to using vim:
vim filename.txt
his command opens the file filename.txt
in the vim editor.
Vim modes:
- Normal Mode: Allows you to navigate through the text, delete lines, copy and paste text. After launching
vim filename.txt
, you usually start in Normal Mode. - Insert Mode: Mode for entering text.
- Visual Mode: Mode for selecting blocks of text.
Switching between modes:
- To enter Insert Mode, press the
i
key in Normal Mode. - To enter Visual Mode, press
v
in Normal Mode. - To return to Normal Mode from Insert or Visual modes, press the
Esc
key.
Saving changes and exiting:
- In Normal Mode, enter
:w
and pressEnter
to save changes. - Enter
:q
and pressEnter
to exit vim. - To save and exit simultaneously, enter
:wq
and pressEnter
. - To exit without saving changes, use
:q!
and pressEnter
. You will exit vim, discarding all changes.
Inserting text:
- In Normal Mode, move the cursor to the desired location.
- Enter Insert Mode by pressing
i
. - Enter the text.
- Return to Normal Mode by pressing
Esc
.
Search and replace:
- In Normal Mode, enter
/
and type the text to search. PressEnter
. - For replacement, enter
:%s/old_text/new_text/g
and pressEnter
.
Vim offers many functions, and mastering all of them may take time. However, once you learn the basic commands, you can efficiently edit text files right from the terminal.
vim
and nano
are two command-line text editors. They have differences in usage style and functionality, but in basic functionality, they converge. In this article, we covered the basic functionality of vim as I prefer using vim for its extended capabilities. You can use nano instead, depending on your preferences and command requirements.
Patterns for Search:
Creating a pattern for commands like find, grep, and similar can be useful for searching and filtering files and data. The pattern is very similar to regex but with reduced functionality. How to create a pattern:
Using metacharacters:
*
Replaces any number of characters.?
Replaces one character.[]
Allows specifying a range of characters.
Examples:
Search for all files with the extension .txt
:
find /путь -type f -name "*.txt"
Finding all files containing “keyword”.
find /path -name "*keyword*"
Creating effective patterns depends on specific search tasks and can be customized according to your particular usage scenario.
In grep, regular expressions can be used for more complex searches; use the -E flag for this purpose.
Conclusion
Bash commands in the terminal are essential for developers, offering a powerful toolset for efficient file and system management. Learning these commands is pivotal for optimizing tasks, managing processes, and gaining control over the file system.