Do you think of the command line as an antiquated leftover from the past, or an old fashioned way of interacting with a computer? Think again. In Linux, the command line remains the most flexible and powerful way to perform tasks. For example, searching for all .tmp files in a directory (and its subdirectories) and then deleting them can be a multi-step process when done via GUI, but it only takes seconds when done through the command line.
In this article, we'll discuss the basics of the Linux command line including directory navigation, file/directory operations, and search. Once you have mastered these, in the second half of this guide, we go deeper to discuss file metadata, permissions, timestamps, and more.
1. What is a home directory in Linux?
Linux is a multi-user operating system, which means that more than one user can access the OS at the same time. To make things easy, each user is assigned a directory where they can store their personal files. This directory is known as a user's home directory.
Home directories are found under the home directory. For example, my home directory is /home/himanshu. Please note that a user's home directory has the same name as their login name. If you are a Windows user, you can think of a Linux home directory as a user specific directory usually present inside C:\Documents and Settings or C:\Users.
Users have complete control over their home directory as well as all its sub-directories. This means that they can freely perform operations like create and delete files/directories, install programs, and more, inside their home directory.
2. How to check the present working directory?
Whenever you open a command line shell in Linux, you start at your home directory. This is your present working directory, which changes as you switch to some other directory. Use the pwd command to check the complete path of your present working directory at any point of time.
Here is an example:
The pwd command output, shown in the screenshot above, indicates that the user is currently in the Pictures directory, which is inside the himanshu directory, which in turn is a subdirectory of the home directory. In this case himanshu@ubuntu:~/Pictures$ is the command line prompt.
3. How to switch directories?
Use the cd command to navigate through the Linux filesystem. This command requires either a directory name or its complete path depending upon where the directory is present.
For example, if your present working directory is /home/himanshu/pictures, and you want to switch to /home/himanshu/pictures/vacations, then you can simply run the command: cd vacations. In this case, the command line shell will search for the vacations directory inside pictures. A path relative to the present working directory is also known as relative path.
But in case you want to switch to /home/techspot, you'll have to run the command: cd /home/techspot. The complete path, that begins with a forward slash (/), to a directory is also known as its absolute path. To quickly switch to the previous directory in the tree, run: cd .., or if you want to switch to the previous working directory run cd -
4. How to view directory contents?
Use the ls command to list the contents of a directory. If the command is run without any argument, it displays the contents of the present working directory.
Here is an example:
To view the contents of any other directory, you can either specify its name (if it's a subdirectory) or its complete path (if it's not a subdirectory) as an argument to the ls command.
If you observe closely, the output of the ls command is color coded. These different colors represent different types of files, making it easy to visually identify them. Some of the basic colors that you should know are: Blue (Directories), White (Text files), Red (Archives), Cyan (Links), Green (Executables), and Pink (Images).
5. How to view the contents of a file?
Use the cat command to view the contents of a file. This command expects a filename as an argument. As you can see in the screenshot below, the cat command displayed the contents of the arg.c file. However, there is a limitation. If the file is large, the output might be too big for the command line shell screen to accommodate.
In that case you can use use the less command along with the cat command: cat [filename] | less. The | symbol represents a pipe, which redirects the output of the cat command to the less command, which in turn makes it possible for you to navigate through the file's content using the arrow keys on your keyboard to scroll up and down. To quit the display mode press the q key.
6. How to create a new file?
Use the touch command to create a new file. The command requires a filename as argument. For example, to create a file named test.log in the present working directory, just run the command: touch test.log.
To create a new file at a location other than the present working directory, use the absolute path. For example, touch /home/himanshu/practice/test.log.
Tip: To write anything into a newly created file, use a command line editor like Vi or Vim.
7. How to rename/copy/delete a file?
Use the mv command to rename a file. For example, to rename log.txt to new_log.txt, run the command: mv log.txt new_log.txt. As always, if the file is not present in the present working directory, use the absolute path.
You can also use the mv command to move a file from one location to other. This is the equivalent of a cut-paste operation via GUI. For example, to move log.txt (present in current directory) to /home/himanshu, run the command: mv log.txt /home/himanshu.
To copy a file from one directory to another, use the cp command. Like the mv command, cp also requires a source and a destination. For example, cp log.txt /home/himanshu would create a copy of log.txt (with the same name) in the /home/himanshu directory.
To remove a file, use the rm command. This command expects a filename as an argument. For example, rm log.txt will remove the text file, if present in the current directory, while rm /home/himanshu/practice/log.txt will remove the text file present inside the practice directory.
To remove directories, use the -r command line option with the rm command. For example, rm -r /home/himanshu/practice/ would delete the practice directory with all its subdirectories and files.
8. How to search for files?
To search for files within a given directory, use the find command. The command requires directory path and filename as argument. For example, to search for a file named inheritance.cpp in the /home/himanshu/ directory, use the find command in the following way:
I used sudo in the find command above to remove certain permission errors. You can skip it.
If a directory path is not specified, the find command searches in the present working directory.
You can also use wildcards with the find command to get the most out of it. For example, if you want to search all .c files present in the /home/himanshu/practice directory, use the find command as shown below. The '*' character is a wildcard that can represent any number of characters. For example, tech* can represent tech, techspot, techreport, and more.
9. How to search text within files?
To search text within files, use the grep command. The command expects a keyword and a filename as arguments, and outputs lines that contain the keyword. For example, to search all the lines in the file /home/himanshu/practice/wazi/gdb/test.c that contain the keyword ptr, use the grep command in the following way:
Use the -n command line option in case you want grep to display line numbers in output.
Tip: To search a keyword in all the files present in the current directory, use the * wildcard character as the filename.
Please note that unlike the find command, the grep command doesn't search within subdirectories by default. However, you can enable this functionality by using the -R command line option while running the grep command.
10. What is the auto-complete feature?
While working on the Linux command line, typing long paths, file names, and more can feel like a burden. Use the tab key to auto complete these long names and paths easily. For example, to write /home, you can just write /ho and press tab. The command line shell will auto complete the name for you.
In the example above, it was easy for the shell to guess the name home because there was no other similar candidate in the / directory. But in case the shell encounters similar names while auto completing, it will display those names and you'll have to write a few more letters for the shell to know the correct name.
Here is an example:
The shell displayed all the names that it can use for auto completion. If, for example, you wanted to write techspot, then you'll have to type in at least c to resolve the ambiguity. Once done, you can hit the tab key again to autocomplete the name.
11. What is root?
Root is the only user that has control over the entire Linux system. It is capable of doing what normal users can't, such as, changing ownership of files, adding or removing files from system directories, and more. As you can guess, the root account is mostly used by system administrators only.
The top level directory in a Linux system, represented by forward slash (/), is known as root directory. It is the same directory that contains the home directory, which further contains user specific directories. However, you shouldn't confuse / with the root user's home directory, which is located under / by the name of root.
12. What are man pages?
To learn more about Linux commands, you can head over to their respective man (or Manual) pages that come preinstalled with Linux. To open a man page, just run the man command followed by the command name. For example, run man rm to open the manual page of the rm command. You can find a lot of useful information about Linux commands this way.
Next up, we build on the essential commands above to discuss file metadata, permissions, timestamps, as well as some new tools like tee and Vim...
13. How to access file metadata like size, permissions, and more?
Use the ls command with -l option to display file metadata in output. For example:
Each line in the output contains metadata information related to a file or a sub-directory present in the current directory. This information can be divided into the following eight parts:
+permissions that apply to the owner
|
| +permissions that apply to all other users
| |
| | +number of hard links
| | |
| | | +file size +last modification date/time
_|_ _|_ | _|___ ________|__
drwxr-xr-x 3 himanshu himanshu 4096 Jul 3 14:26 Desktop
__ ________ ________ ______
| | | |
| | | +name of file/ directory
| | |
| | +group the file belongs to
| |
| +owner of the file
|
+permissions that apply to the members of the group the file belongs to
The first character represents the file type. For example, in the line shown above, d indicates this is a directory. Other values can be: - for normal file, s for socket file, l for link file, and more.
The next 9 characters represent permissions – r - read, w - write, x- execute. The first set of three characters represents the owner's permission, the next three are group's permission, and the final three represent permissions granted to others who are neither the owner, nor the part of the group the file belongs to. In the example shown above, the owner has read, write and execute permissions, while the group as well as others both have only read and execute permissions.
Tip: Use the -h command line option along with -l to display file size in human readable format.
14. How to change file permissions?
Use the chmod command to alter file permissions. There are two ways in which this command can be used. The first method, also known as letters method, uses +, -, and = signs to add, remove, and assign permissions. Letters a, o, u, and g represent all, others, owner, and group respectively.
For example, the chmod u=rwx somefile command assigns read, write, and execute permissions to the owner of the file somefile. Similarly, the chmod o+w somefile command adds write permission for others, the chmod g-r somefile removes read permission from the group the file belongs to, and the chmod a+x somefile command adds execute permission for everyone.
Specifying a is not mandatory, which means that setting permissions like +x or -r without specifying owner, group or other automatically applies it to all.
The second method is the numbers method and it uses 4, 2, and 1 instead of r, w, and x. The values are added together in sets of 3 to give us a three digit number denoting permissions.
For example, the chmod 761 somefile command gives rwx, rw, and r permissions to the owner, group, and others, respectively. Here 7 represents the sum of numbers corresponding to r,w, and x. Similarly, 6 represents the sum of numbers corresponding to r and w, while 1 represents x.
15. How to change file timestamps?
Use the touch command to change file timestamps. There are three types of timestamps associated with a file: Access time, Modification time, and Change time. While the first two are self explanatory, the third one represents the time when the inode information or the meta data related to file last changed. Use the stat command to display these timestamps:
To change the file access time to the current time, use the touch command with the -a option: touch -a somefile. Similarly, the -m option changes the file modification time to the current time.
To change file timestamps to a time other than the current time, use the -t command line option. For example, the command touch -t 201407020900.01 -a somefile changes the access timestamp of somefile to 2014/07/02 09:00:01. You can also pass a specific date and time in human readable form. Use the -d command line option for this. Here are some examples:
touch -d "2013-01-10 10:00:07" -a somefile
touch -d "next sunday" -m somefile
touch -d "3 hours ago" -a somefile
16. How to determine file types?
Use the file command to determine file types. As shown in the example below, the command expects a filename as an argument. You can also use the wildcard * in place of file name to display the file type for every file in the current directory: file *
17. I've downloaded an executable file, but it doesn't execute, why?
In Linux (and other *nix systems) whether a file is executable or not depends solely on its permissions, not on its extension or content. When a file is downloaded, its original permissions are not known, and is hence given a default set of permissions that are determined by umask.
If the user really intends to execute the downloaded file, they'll have to explicitly give executable permissions to it using the chmod command explained above. Giving permissions manually also helps prevent virus, worms, and more from infecting your system without your knowledge.
18. How to print the number of new lines, words, and bytes in files?
Use the wc command to print newline, word, and byte counts for a file. Here is an example:
In the output shown above, 5 represents the number of lines, 12 represents the number of words, and 52 represents the number of bytes. You can also use the -l, -w, and -c command line options to separately produce number of lines, words, and bytes, respectively in the output.
19. How to display disk usage of files and directories?
Use the du command to display disk usage of files and directories. Here is an example:
Note - The -h command line option is used to produce the size in human readable format.
An important thing to note here is that the du command outputs the resident size of a file, which could be different from the actual size that the ls -l command displays. The reason behind this difference is either slack space or sparse files.
To display the combined size of a directory as well as all its subdirectories, use the -s option, while -S can be used to display separate sizes. To display the amount of disk space available on the file system containing a specific file or directory use the df command.
Here again, the -h option is used to display the output in human readable format. If the df command is run without any file/directory name, it'll show disk usage for all the file systems.
20. How to compare two files?
Use the diff command to compare two files. The command examines both the files and produces the output in a particular format to let you know what changes are required for the files to match. The command requires two filenames as arguments, as shown in the example below.
Use the diff command to compare these files:
Decrypting the output shown above, 5c5 means that the fifth line of somefile is changed, and should be replaced by the fifth line of the file anotherfile. The line in question from the first file is marked with a < symbol, while line from the second file is marked with a > symbol.
Note- Besides c, which signifies a changed line, the diff command also points which lines need to be added (a) and deleted (d) for the files being compared to match.
21. How to view the first few and last few lines of a file?
Use the head and tail commands to quickly view the first and last few lines of a file. These commands come in handy when you just want to have a quick peek inside the file. For example, the head -n2 somefile command displays the first 2 lines of the file somefile. Similarly, the tail -n3 somefile command displays the last 3 lines of the file.
Not only lines, you can also quickly view a specified number of bytes using these commands. For this, use the -c command line option instead of -n. By default, when the number of lines is not specified, both the commands display 10 lines in the output.
22. How to store and view the output of a command at once?
Use the tee command to simultaneously write the output of any other command to standard output as well as to one or more files. For example, the ls | tee ls-dump command displays the output of the ls command on console and stores the output in the file ls-dump.
While the tee command is mostly used for capturing and analyzing logs at the same time, it can also be used to speed up your workflow. For example, the echo "Linux command line" | tee file1 > file2 command writes the string to both files in one go.
23. How to compress and uncompress a file?
Working on Linux requires you to deal with archives like .tar, .tar.gz, .bz2, and more. To create as well as uncompress these archives you can use the tar command.
For example, the tar -cvf practice.tar practice/ command compresses the practice folder and creates a .tar archive named practice.tar. The -c command line option tells the tar command to create an archive, -v displays the files added to the tarball , and -f specifies the filename.
To uncompress the .tar archive created above, use the tar -xvf practice.tar command. The -x command line option signals the command to extract the archive. This command untars the file in the current directory. Use the -C option to specify a different target directory.
To create .tar.gz and .tar.bz2 archives, add an extra -z and -j command line option, respectively. The command to uncompress these archives is same as the one used for .tar files. Use the -t command line option (along with v and f) in case you just want to list the contents of an archive.
Tip - To deal with .zip files, use the zip command.
24. How to edit a file using Vim editor?
While the Vim editor is one of the most powerful command line text editors, it also requires you to learn a lot of keyboard shortcuts. But the basics of editing are simple and easy.
To open a file in the editor, run the vim command with the file name as an argument
There are two operation modes in Vim: command mode and insert mode. The editor opens the file in command mode, where you can move the cursor using the arrow keys on your keyboard, but cannot edit the file until you press i – activating the insert mode as shown below.
Once you are done editing the file, you have to press the Esc key to come out of the insert mode and into the command mode before being able to save the file.
To save the file, type the :w command and then hit Enter.
To quit the editor, type the :q command and press Enter, or :wq to save and quit in one go.
Note - To quickly copy or delete a line, switch the editor to the command mode, bring the cursor to the desired line, and type yy or dd, respectively. To paste, press p in the command mode.
Wrap Up
While it may seem antiquated in this day and age of modern operating systems, the command line remains the most flexible and powerful way to perform tasks in Linux. We've barely scratched the surface here, as the Linux command line has much to offer.
Each command mentioned in the article is capable of doing a lot more than what we've discussed, but this should give you an overall grasp of their use. If you get stuck somewhere, leave us a comment or head over to our Software & Apps forum.
Note: This feature was originally published in June 2014. We have revised and bumped it because it's as relevant today as it was before if you are learning the Linux ropes. Part of our #ThrowbackThursday initiative.