Bash Commands in Linux With Examples

Welcome to our guide on “Bash Commands in Linux.” In this article, I’ll introduce you to some important tools you can use in the Linux terminal. We’ll explore variables in bash, and some basic operations used along with bash like copying files, displaying text, moving and deleting files, listing directories, and searching for specific words. These commands will boost your productivity. So, welcome aboard as we embark on an exciting journey into the world of Bash commands in Linux! Let’s get started!

Bash is a shell in Linux. It is default shell in most of the Linux based distros. Until now, even Mac used it as default shell. Using it you can execute any command.

It is a POSIX compliant shell so whatever commands I teach you here most of them will be applicable in other POSIX compliant shells like dash, zsh, etc.

📝 Note: These commands have been tasted on Linux. But they should work with any Unix based system such as Mac and Windows Subsystem for Linux.

Variables in bash commands in Linux

To learn about what are variables, how to define them, put a value inside a variable and get a value out of variable, look at this article.

Here, I am going to describe these in short.

Variables are defined in the following way:

[ajay@legion ~]$ variable=value

Examples for Integer:

[ajay@legion ~]$ x=3

Examples for String:

[ajay@legion ~]$ y="ajay_yadav"

It is good to always use quotes around your values, otherwise, you might get errors caused by “splitting”, or “substitution”. They are not errors per se. These splitting and substitution have a special application. I will talk about them in later articles.. Example:

[ajay@legion ~]$ y="ajay yadav"

Output of a variable in bash shell in Linux

To get the value of a variable, prepend $ just before it. For example, to get the value of x, use $x.

[ajay@legion ~]$ x=3
[ajay@legion ~]$ echo "$x"
3

Another useful bash feature is brash expansion. Have a look about that in this article.

Some important tools used with bash command in Linux

Commands like pwd, cd, mv, cp, touch, rm, echo, ls, grep etc. are very useful basic commands in Linux. They are not part of bash per se. But they are used very often. So, please learn them as you learn bash. I am going to give you short description of each.

😄 Note: Most of these commands like mv, cp, rm works in the same way. You will see as I describe all of them below.

copy command in Linux

Here are the few copy command cp I use while working with bash commands in Linux. To learn about the cp command in detail, look at this article.

To copy file1‘s content into file2 execute:

[ajay@legion ~]$ cp file1 file2

If file2 exists, its contents are replaced. If you use directory name at the place of file2, file1 will be copied to that directory.

For verbose output, use -v:

[ajay@legion ~]$ cp -v ~/Downloads/10th.pdf .
'/home/ajay/Downloads/10th.pdf' -> './10th.pdf'

For cp in interactive mode, use -i:

[ajay@legion ~]$ cp -v ~/Downloads/10th.pdf .
'/home/ajay/Downloads/10th.pdf' -> './10th.pdf'

[ajay@legion ~]$ cp -i ~/Downloads/10th.pdf .
cp: overwrite './10th.pdf'? y
[ajay@legion ~]$ cp -vi ~/Downloads/10th.pdf .
'/home/ajay/Downloads/10th.pdf' -> './10th.pdf'

[ajay@legion ~]$ cp -vi ~/Downloads/10th.pdf .
cp: overwrite './10th.pdf'? y
'/home/ajay/Downloads/10th.pdf' -> './10th.pdf'

To copy one directory into another, use -r or --recursive:

[ajay@legion ~]$ cp -r /tmp/from/ /tmp/to/

echo command in Linux

To learn about the echo in detail, look at this article on echo.

The echo command in Linux is used to display text or output messages to the terminal. It is a simple and versatile command that comes in handy while writing bash scripts.

To display a message, just use echo followed by the text you want to show:

$ echo "Hello, World!"
Hello, World!

The echo command can also be used to print the values of variables:

$ name="Alice"
$ echo "Hello, $name!"
Hello, Alice!

Moreover, you can redirect the output of echo to a file using the > operator:

$ echo "This will be saved in a file." > output.txt

The text “This will be saved in a file.” will be written to a file named output.txt.

echo is often used in bash scripts to provide information to users, display status messages, or generate program output. It is a fundamental command that simplifies displaying text and variables in the terminal.

pwd command in Linux

Another useful command in Linux is pwd, which stands for “Print Working Directory.” When you run the pwd command, it displays the full path of your current working directory:

[ajay@legion ~]$ pwd
/home/ajay

This is particularly handy when you’re navigating through different directories and want to know your current location. For instance, if you move to a subdirectory like Documents, the pwd command will show:

[ajay@legion ~]$ cd Documents
[ajay@legion Documents]$ pwd
/home/ajay/Documents

The pwd command becomes essential when dealing with complex file structures, or whenever you need to reference your current location in the bash scripts. It provides a clear and concise way to keep track of your working directory and facilitates smooth navigation within the Linux environment.

cd command in Linux

Let’s explore another fundamental command in the Linux terminal – cd, which stands for “Change Directory.”

With the cd command, you can navigate through the file system and switch between different directories effortlessly. To change the working directory to a specific location, simply type cd followed by the desired directory path:

[ajay@legion ~]$ cd Documents

After executing the above command, you will find yourself in the “Documents” directory. To go back to the previous directory, you can use cd with the .. notation, like this:

[ajay@legion Documents]$ cd ..
[ajay@legion ~]$

This takes you back to your home directory. If you ever need to return to the home directory from anywhere else, just type cd with no arguments:

[ajay@legion Downloads]$ cd
[ajay@legion ~]$

Moving and Renaming Files with mv

The mv command in Linux is used to move or rename files and directories. It allows you to change the location or name of a file within the file system. Here’s how you can use the mv command:

To move a file or directory from one location to another:

mv source_path destination_path

For example, to move a file named file1.txt from the current directory to the Documents directory:

mv file1.txt Documents/

This will move file1.txt to the Documents directory.

To rename a file or directory:

mv old_name new_name

For instance, if you want to rename file1.txt to new_file.txt:

mv file1.txt new_file.txt

This will rename the file to new_file.txt.

If a file with the same name exists in the destination directory while moving, mv will overwrite it. To avoid accidental overwrites, use the -i (interactive) option:

mv -i source_path destination_path

This will prompt you before overwriting any existing files.

For a more verbose output, you can use the -v (verbose) option:

mv -v source_path destination_path

This will display each action taken by mv, providing you with more details.

Keep in mind that if the destination path is a directory, the source will be moved into that directory. However, if the destination path is a non-existing directory, mv will rename the source file to the new name.

Using the mv command, you can easily organize and manage your files and directories in the bash script.

touch command in Linux

Another useful tool is touch used with bash commands in Linux. If you’re interested in a detailed explanation of the touch command, you can refer to this informative article.

The touch command in Linux is a versatile utility used primarily to create new, empty files or update the timestamp of existing files. It is particularly useful when you need to create a new file quickly or modify the last access and modification times of a file.

To create a new empty file, simply type touch followed by the desired file name:

[ajay@legion ~]$ touch new_file.txt

This command will generate a new file named new_file.txt in your current working directory. If the file already exists, the touch command will update its modification timestamp to the current time without altering the file’s content.

Moreover, touch allows you to set specific timestamps for files using the -t option. The following example shows how to set a custom timestamp for a file:

[ajay@legion ~]$ touch -t 202207221030 custom_timestamp.txt

In this case, the custom_timestamp.txt file will have a timestamp of July 22, 2022, at 10:30 AM.

rm command in Linux

The rm command, which stands for “remove,” is a powerful and potentially dangerous tool used to delete files and directories in the Linux terminal. It allows you to permanently remove files from the file system, and it’s essential to exercise caution while using this command, as deleted files cannot be easily recovered.

To delete a single file, use the rm command followed by the file name:

[ajay@legion ~]$ rm unwanted_file.txt

Once executed, the file unwanted_file.txt will be deleted, and it cannot be retrieved from the system’s trash or recycle bin.

To remove multiple files simultaneously, you can specify them as arguments with space separation:

[ajay@legion ~]$ rm file1.txt file2.txt file3.txt

The rm command also supports the use of wildcard characters, such as *, to remove files based on specific patterns:

[ajay@legion ~]$ rm *.txt

In this example, all files with the .txt extension in the current directory will be deleted.

If you want to remove directories, you can use the -r or --recursive option with rm:

[ajay@legion ~]$ rm -r unwanted_directory/

The -r option ensures that all files and subdirectories within the specified directory are recursively removed.

To minimize the risk of accidental deletions, you can use the -i or --interactive option, which prompts you for confirmation before removing each file:

[ajay@legion ~]$ rm -i sensitive_file.txt
rm: remove regular file 'sensitive_file.txt'? y

Always double-check the files and directories you are about to delete, especially when using the -r or -i options.

ls command in Linux

The ls command is one of the most basic and frequently used with bash commands in Linux. It stands for “list” and is used to display the contents of a directory. By default, when you run the ls command without any arguments, it lists the files and directories in your current working directory:

[ajay@legion ~]$ ls
Desktop    Documents    Downloads    Music    Pictures    Videos

The output displays the names of the files and subdirectories present in the current directory.

To list the contents of a specific directory, simply provide the directory path as an argument to the ls command:

[ajay@legion ~]$ ls /path/to/directory
file1.txt   file2.txt   subdirectory1   subdirectory2

The ls command also offers several useful options to customize the listing output. For example, you can use the -l option to obtain detailed information about the files and directories, such as permissions, owner, size, and modification date:

[ajay@legion ~]$ ls -l
-rw-r--r-- 1 ajay users  4096 Jul 28 10:15 file1.txt
-rw-r--r-- 1 ajay users  2048 Jul 28 10:20 file2.txt
drwxr-xr-x 2 ajay users  4096 Jul 28 10:30 subdirectory1
drwxr-xr-x 3 ajay users  4096 Jul 28 10:35 subdirectory2

For a more human-readable file size representation, use the -h (human-readable) option:

[ajay@legion ~]$ ls -lh
-rw-r--r-- 1 ajay users 4.0K Jul 28 10:15 file1.txt
-rw-r--r-- 1 ajay users 2.0K Jul 28 10:20 file2.txt
drwxr-xr-x 2 ajay users 4.0K Jul 28 10:30 subdirectory1
drwxr-xr-x 3 ajay users 4.0K Jul 28 10:35 subdirectory2

You can also use the -a (all) option to display hidden files (those starting with a dot):

[ajay@legion ~]$ ls -a
.        ..        .config   .bashrc   file1.txt    file2.txt

grep command in Linux

let’s explore the grep command in Linux. For a more comprehensive understanding of the grep command, you can refer to this informative article.

The grep command is a powerful text search tool used in Linux to find patterns or specific strings within files or streams of text. It stands for “Global Regular Expression Print,” and it’s one of the most versatile commands for text processing and filtering.

The basic usage of grep is as follows:

[ajay@legion ~]$ grep pattern file.txt

In this example, pattern represents the text you want to search for, and file.txt is the file you want to search within. The grep command will then display all lines in file.txt that contain the specified pattern.

For example, let’s say we have a file named sample.txt with the following content:

Hello, this is a sample text file.
This file contains some sample data.
Please search for the word "sample".
This is fourth line

To find all occurrences of the word “sample” in sample.txt, you would run:

[ajay@legion ~]$ grep "sample" sample.txt
Hello, this is a sample text file.
This file contains some sample data.
Please search for the word "sample".

By default, grep is case-sensitive. However, you can use the -i option to perform a case-insensitive search:

[ajay@legion ~]$ grep -i "hello" sample.txt
Hello, this is a sample text file.

grep is highly flexible and supports regular expressions, allowing you to perform complex pattern matching. For example, using regular expressions, you can search for lines starting with a specific word:

[ajay@legion ~]$ grep "^Hello" sample.txt
Hello, this is a sample text file.

To count the number of occurrences of a pattern, use the -c option:

[ajay@legion ~]$ grep -c "sample" sample.txt
3

In this case, grep returns the number “3,” indicating that the word “sample” appears thrice in the sample.txt file.

The grep command is an invaluable tool for searching and extracting information from text files efficiently. It is widely used in scripting, log analysis, and various data processing tasks, making it a must-know command for Linux users.

Another most widely used command in bash is printf – learn about it here.

Conclusion

That’s all about folks. Most of these tools are used frequently with bash commands in Linux. So learn more and more about them. If you have any suggestions/queries, read the man page at man bash, man ls, man cp and other relavant commands related to bash. Or, you put them in the command section below. If you are not satisfied with the features provided by the bash, you can look at another POSIX compliant shell but much powerful than the bash – zsh.

Leave a Comment

Your email address will not be published. Required fields are marked *