Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 17, 2022 01:36 pm GMT

How To Use The Linux Command Line

This is a fairly straightforward article that I wrote so that I can refer to it when I need something in the future. I tried to cover the fundamentals as well as some incredibly magical things that will give every new Linux user the feeling that they have superpowers at their fingertips.

In this article, we will start with the most basic Linux commands and progress to understanding how everything works in Linux terminals until learning about some super cool stuff like the pipe command, including the tee and xargs commands & at the same time you will also learn about various commands and utilities that we will use while we are practicing the same, and at last, we will use some very handy Linux utilities to enhance the productivity, so without further ado, let's get started.

Linux Command Line Basics

Common Commands in Linux

Lets start with the most basic bash commands starting with the echo command.

The echo command prints the strings passed as arguments. This is mostly used in shell scripts to print the status out to the terminal.

// Basic Syntax// echo [option] [string]

Bash basics

Now, if you're lazy like me and want to open a calendar in a GUI, simply use the cal command, which will print a simple calendar in the terminal itself.

// Basic Syntax// cal [[month] year]$ cal

cal command

$ cal 12 12// This will print the Dec'12 calendar

Linux Cal Command

The Date command is mostly used to print the date to the terminal and and to set the system date. Using date command, it is possible to print date in different formats and also to calculate dates.

// Basic Syntax// date [OPTION]... [+FORMAT]$ date// prints day of the week, day of the month, month, year, time and timezone// Sunday 19 June 2022 12:39:26 PM IST

linux date command

If you wish to reuse one of the commands from your terminal session without having to retype the full command, you may use the history command, which will output all of the commands from that terminal session.

// SYNTAX$ history

linux history command

If you wish to rerun one of these commands, just input the command line number preceded by an ! mark.

history command

Data Streams

Now that we are familiar with the basics of the command line, let's learn how everything in the Linux command line functions so that we can optimise the various utilities and boost our productivity. Let's study Linux command line data streams:

There are 3 different Data Streams in Linux as follows:

  1. Standard Input, abbreviated as stdin
  2. Standard Output, abbreviated as stdout
  3. Standard Error, abbreviated as stderr

Standard Input consists solely of the commands you enter into the terminal to perform out particular operations. Standard output is the output that prints from your commands on your terminal screen, and Standard Error is the message that outputs errors from your commands on your terminal.

data streams

Here the ls command is the Standard Input for the terminal and the list of directories printed on the screen is the Standard Output.

Because these are data streams, we can send them somewhere other than your terminal, just like we can write them to a file. These data streams also have number designations as follows:

Standard Input0
Standard Output1
Standard Error2

We can write the output of these commands to different files using redirection operators. Redirection operators in linux are as follows:

Input Redirection<
Output Redirection1>
Output Redirection (appends)1>>
Error Redirection2>
Error Redirection (appends)2>>

Lets try redirection operators by redirecting some of the outputs in action:

Lets use the ping command to check the connectivity between the local machine and the server.

ping command with redirection

Now I m getting the output on the same screen, lets redirect the output of the following command to output.txt file.

$ ping -c 10 google.com > output.txt

And now you'll see that nothing prints on your terminal screen after running this command.

Linux command Line

This is because you redirected the output to the output.txt file using > redirection operator. Now lets check if the redirection process executed successfully or not by using the cat command to print the contents of output.txt file.

redirecting pipes in linux

You'll see that the output.txt file now just contains the standard output of the ping command with youtube.com as the destination, rather than google.com. This is because the > redirection operator truncates the standard output to the files when writing, but the >> redirection operator appends the data to the same file. Try with appending the data using the ping command and >> redirection operator, with different destinations redirecting to the same output.txt file.

redirection pipelines in linux

And, as shown in the above image, rather of clearing and writing to the output.txt file, the data is appended to it this time. Now try the following ping command but with an invalid destination so that we generate an error from the command.

$ ping -c 10 google.m >> output.txt

ping command with redirection

Now lets redirect the error message using error redirection operator: 2>> to the errors.txt file using the following command and then print the contents of it using the cat command.

$ ping -c 10 google.m >> output.txt 2>> errors.txt

error redirection in bash terminal

And, as you can see, the error message was successfully redirected to the errors.txt file.

Did you know that? In Linux, everything, literally everything, is considered a file, and terminals are no exception. Because terminals are considered files, you may redirect the output of one command from one terminal screen to another hahah. All you have to do is open two different terminals on your machine and identify the file names of your two different terminals using the tty command.

redirection bw terminals

You will now use the following command to redirect the standard output from your /dev/pts/0 terminal to your /dev/pts/1 terminal:

$ echo "Hello from /dev/pts/0" >> /dev/pts/1

redirection bw terminals

As you can see, we were able to successfully redirect the standard output from one terminal to the other. And I know you feel like a superhero now having super power in your hands ahaha!

Now, let's talk about another utility that can help you increase your efficiency with terminals. This is the Linux Pipe Command, which allows you to combine two or more commands such that the output of one command becomes the input to the next.

The syntax is straightforward; simply insert a vertical symbol (|) between the two commands.

// SYNTAX$ command 1 | command 2 | command 3 | command N

Let's say you want to know how many configs you're using in one of your projects. Instead of opening the file and counting one by one, you'll use the pipe command with the word count utility to count the number of lines in that specific file. To read the number of lines in a file, use the cat command to display the file contents and the wc command to print the number of lines and connect them using the pipe command:

$ cat config/dev.env | wc -l// prints 3

If you wish to use the ping command but are only interested in the results, you may use the ping command with few options and the tail command to simply display the result/summary of the ping process. To do the same thing, use the following command:

$ ping google.com -Ac 10 | tail -3

The -Ac options are the same as the ones we used with the ping command; the -A option speeds up the procedure, the -c 10 option specifies the number of packets to stop after and the pipe command feeds the output of the ping command to the tail command, which outputs the last specified lines of output, which in this case is 3. The following is the output of the preceding command:

ping command in linux

Tee Command

Assume you want to store the results of the same ping command to one file while also saving each packet's information to another, and here is where the Tee command comes in handy. You have to use the Tee command with the pipe command to execute different operations on the same standard output of these commands.

// Syntax$ tee [options] [files]

Now, use the following command to store the ping command result to the results.txt file and the packet details to the packets.txt file:

$ ping google.com -Ac 10 | tee packets.txt | tail -2 >> results.txt

The tee packets.txt command will redirect the output of the ping command to the packets.txt file while also filtering the packets information using tail -2 and storing the statistics to the results.txt file.

Xargs Command

Now that you have heavily used pipes and redirections with your ping command and if you want to get rid of all the files on your machine, you can either use the rm -rf command to delete files by typing each and every file name in your terminal or you can simply use the xargs utility, which allows you to treat the stdout of one command as an argument to the next. Assuming that all of your files are in a single directory, all you have to do is print the files in that directory using the ls command and then use the pipe command with xargs to pass the output to the following command to remove all of the files, which is rm -rf.

$ ls | xargs rm -rf

xargs command in linux

As you can see, we had 10 different files earlier, and we removed all of them with just one command using the xargs utility, which passes the output of one command as arguments to the following command. You may alternatively make a new file called filesToBeDeleted.txt and enter the names of all the files you wish to remove, and then use the cat and rm -rf commands, along with the pipe and xargs commands, to do the same.

$ cat filesToBeDeleted.txt | xargs rm -rf

Aliases

Imagine you're working with Docker and while printing all the containers, your output screen is only as clear as my future; hardly understandable lol.

aliases in linux

And you start googling stuff to format the output, and as usual, Google comes through with a custom command for formatting the output of Docker containers that looks like this:

$ docker ps -a --format="ID{{.ID}}
NAME{{.Names}}
Image{{.Image}}
PORTS{{.Ports}}
COMMAND{{.Command}}
CREATED{{.CreatedAt}}
STATUS{{.Status}}
"

And now, thanks to this custom command, your output screen is clearly separated and very easy to understand:

Linux Command Line Basics

After a few days, you begin working on some other docker project and find yourself in need of the custom formatting command again, which results in the distraction of repeatedly Google everything for the same command every now and again, and this is when Linux Alias comes in handy! Alias allows you to build a shortcut for such daunting long commands so that you don't have to Google them all the time. Aliases are classified into two types: temporary and permanent. Temporary Aliases can be used throughout the same session, but once the terminal is closed, the alias cannot be used in another session.

Creating Temporary Aliases is quite straightforward; the syntax is as follows.:

// SYNTAX$ alias <name>=`<someDauntingCommand>`// The command should be in quotes and there should be no // white spaces between alias name, `=` sign and command.

Open your terminal and run the following command to create an alias for the custom docker format command:

    $ alias dockerformat='docker ps -a --format="ID{{.ID}}
NAME{{.Names}}
Image{{.Image}}
PORTS{{.Ports}}
COMMAND{{.Command}}
CREATED{{.CreatedAt}}
STATUS{{.Status}}
"'

And now all you have to do is just use your shortcut command or the alias you created right now that is dockerformat in your terminal and wait for the magic

aliases in linux

As previously mentioned, temporary aliases are only effective as long as you do not close the terminal window, and it is around this point where you can explore permanent aliases.

You must use the same syntax as for temporary aliases when creating permanent aliases, but you must save it to a file. Let's create a permanent alias for your same docker containers custom formatting command.

  • Create a new file named .bash_aliases in your /home directory. If you want you can actually add these aliases into the same .bashrc file but for keeping things tidy and seperate we will be using .bash_aliases file. To create a file use the following command:
$ nano .bash_aliases// nano is a simple terminal-based text editor.
  • Now, in the .bash_aliases file, add your aliases using the same command that we used to create the temporary alias.
alias dockerformat='docker ps -a --format="ID{{.ID}}
NAME{{.Names}}
Image{{.Image}}
PORTS{{.Ports}}
COMMAND{{.Command}}
CREATED{{.CreatedAt}}
STATUS{{.Status}}
"'
  • When you've finished adding your alias to the file, hit Ctrl + O and then Enter key to save it, then Ctrl + X to exit the nano text editor and return to the terminal.
  • Now, use the following command to tell your terminal to look for custom commands in your freshly created .bash_aliases file:
$ source ~/.bash_aliases
  • Aaah, that's it, you've successfully added the permanent alias to your machine. Test it out by using your newly added permanent alias.

Aliases in Bash

Alias Story Time*: (The great deal of Dumbfuckery I did!)*

Please make sure that you are not overriding any shell builtin command with your own alias command, or else your terminal will always believe that you are attempting to use your alias rather than the original builtin command. I found the shutdown -P now command incredibly handy for every time I needed to turn off my machine (just once a month but yes), but typing the entire command was not very easier, so I made an alias for the shutdown command and named it sh. So, after a month or so, when I wanted to switch my terminal from bash to shell, the built-in command for doing so is, yeah of course, sh, and every time I used sh, my machine used to shut down abruptly, and I wasted my entire day identifying why that was happening for no reason, and then after hours of googling, my mind asked me to check aliases, and I was like huhhhhh! Please do not override any built-in command in order to save yourself hours of utterly pointless googling.

DMs are open here:)


Original Link: https://dev.to/sankalpswami1122/how-to-use-the-linux-command-line-khl

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To