Best Way to Edit sudoers File in Linux

In Linux, the sudoers file present in the /etc directory will determine the permissions and other settings  while the sudo command is used. If you edit the file directly using terminal or using an editor, if there is any error in your code, the whole sudo command will break. So it is not the best way to edit the sudoers file.

The best way to edit the sudoers file is to use the following command :

$ sudo visudo

This will open the sudoers file in vi editor and you will be able to edit the file here. Once you try to save, it will check for errors and will let you know the same with options to save, not save or re-edit the file.

So it is the safer option while trying to edit sudoers file.

How to Create Directory Structure using Terminal

In this article, we are going to see how to create a directory structure using terminal.

The “mkdir” command  is used to create a folder or a directory using terminal. Now for creating a folder within another folder (multilevel directory structure), if  you use the “mkdir” command like the following command, you will get one error message like this “mkdir: dir1/dir2: No such file or directory”.

$ mkdir dir1/dir2/dir3

Now if you want the terminal to create the structure itself when you try to create a directory, you will have to use the command like this :

$ mkdir -p dir1/dir2/dir3

This will first create the directory, “dir1”, then inside dir1, it will create the directory “dir2” and finally inside dir2, it will create the directory “dir3”.

Single Line Conditional Statement for Terminal

In terminal, it is possible for you to write single line conditional statements, where you can execute a single line of statement if a condition satisfies or otherwise.

Here is the command which you can use.

$ [ -d yourfolder ] && echo “Directory Exists.” || echo “Directory does not exists.”

This command will first check whether there is a file named “yourfolder” in the current location and based on the result, it will decide which statement to execute.

Here if the folder is there, then it will display the line “Directory Exists.” in the terminal and if the folder is not there, then it will display the line “Directory does not exists.”.

How to Create a Directory if Not Already Created using Terminal

In this article, we are going to see how to check whether a directory is that or not in terminal and create the directory if not already there.

For this, then you can use the following command :

$ [ -d yourdirectory ] || mkdir yourdirectory

This is similar to an if condition. First it will check whether there is a directory name “yourdirectory” in the current path and if the directory is there, then it will do nothing. But if the directory is not there, it will create the directory.

How to Delete a Folder using Terminal

In this article, we are going to see how to delete a folder using terminal.

If you want to delete an empty folder, then you can use the following command :

$ rmdir emptyfoldertodelete

This will delete the folder if it is empty. But if the folder is not empty, then it will display one error message like this.

rmdir: emptyfoldertodelete: Directory not empty

If you want to delete the folder which is not empty, then you can use the following command :

$ rm -r foldertodelete

This will delete the folder even if the folder is not empty.

How to Delete the Contents of a Folder using Terminal

In this article, we are going to see how to delete the contents of a folder using terminal without deleting the folder itself.

For this, you can execute the following command :

$ rm -r “yourfoldernamewithpath/“*

This command will remove all the contents of the folder that you specify without deleting the folder. Please ensure that no space is there between the file name and *

Linux ‘Locate’ Command Explained

The locate command is often the simplest and quickest way to find the locations of files and directories on Linux and other Unix-like operating systems.

The basic syntax for locate is:

locate [options] name(s)

When used without any options, locate displays every absolute pathname for which the user has access permission that contains any of the names of files and/or directories that are provided to it as arguments (i.e., input data).

The absolute pathname, also referred to as the absolute path or the full path, is the hierarchy of directories from the root directory to the designated file or directory. The root directory is the directory at the very top of the filesystem (i.e., hierarchy of files) that contains all other directories and files on the system and which is designated by a forward slash ( / ). It is important that the absolute pathname is returned both because it tells the exact locations on the system and because it makes it possible to indicate the locations of files or directories that have the same name but different absolute paths.

Thus, for example, the following would list the absolute paths of all files named file1 and all directories named dir1 for which the user had access permission:

locate file1 dir1

It would also list any other absolute pathnames that contained these strings (i.e., sequences of characters), for example /home/john/file123 or /usr/local/mydir1/index.html.

The specificity of locate can be increased by using it together with wildcards or other regular expressions. Wildcards are characters that can be used to substitute for any other character or characters. For example, the star character ( * ) is a wildcard that can represent any single character or any string containing any number of characters. Regular expressions are a string that describes or matches a set of strings, according to certain syntax rules. For example, the following command uses the star wildcard to display all files on the system that have the .png filename extension:

locate “*.png”

The -q option is used to suppress error messages, such as those that might be returned in the event that the user does not have permission to access designated files or directories. Thus, the following would suppress any error messages in the above example:

locate “*.png” -q

It is often the case that a large number of results will be returned for any query. The -n option followed by an integer limits the results to a specific number. For example, the following command would display only 15 results in a search for files that have an .html extension:

locate -n 15 “*.html”

An alternative is to use a pipe (represented by the vertical bar character) to redirect the output of locate from the display screen to a pager such as more or less, which presents only one screenful of output at a time, for example,

locate “*.html” | less

The -i option performs a case-insensitive search. That is, it will return any results that match the arguments regardless of whether individual letters are lower case or upper case. For example, the following would return all files with the extension .html, .HTML, or some combination thereof:

locate -i “*.HtmL”

On some systems, such as Red Hat, the program slocate is installed by default instead of locate, and entering the locate command activates a script (i.e., a short program) that causes slocate to be launched. slocate provides a secure way to index and quickly search for files on a system by storing file permissions and ownership data so that users will not see files for which they do not have access.

The -V option can be used to show which version of locate is used, including whether it is locate or slocate. Another way to determine whether slocate is being used is to see if an absolute pathname such as /usr/bin/slocate is returned when the following command is issued:

locate locate

locate and slocate actually search a built-in database, named locate.db or slocate.db, respectively, rather than the entire hard disk drive itself, in order to provide a much shorter searching time. This database is automatically updated on a regular basis by cron, a small program that runs in the background, performing various tasks at regularly scheduled intervals. The updating is performed each night if the computer is on continuously.

Because the database is not updated immediately, recently created files and directories might not show up when searching for them with locate or slocate. Fortunately, however, it is a simple matter to update the database manually, although it might take a few minutes. Manual updating can be accomplished by logging in as the root user (i.e., administrative user), such as by using the su (i.e., substitute user) command, and then issuing the following command:

updatedb

The same thing can be accomplished by the root user by using locate with its -u (i.e., update) option, i.e.,

locate -u

For the curious, the database is located at /var/lib/slocate/slocate.db on some systems, such as Red Hat. Its exact location on any particular system can be found by the root user (because ordinary users will not have access permission on most systems) with the locate command as follows:

locate locate.db

The database is a binary file (i.e., a non-text file). However, for the really curious user who has root permission, the human-readable portion of its contents can be viewed by first using the strings command to extract all the plain text and by then piping the output to less for displaying one screenful at a time as follows:

strings /var/lib/slocate/slocate.db | less

If it is desired to perform a more sophisticated search, including searching by attributes other than name (e.g., by size, creation date or location), the find command should be used.

Courtesy – Linfo

Linux ‘Du’ Command Explained

The du Command – shows the sizes of directories and files.

The du (i.e., disk usage) command reports the sizes of directory trees inclusive of all of their contents and the sizes of individual files. This makes it useful for tracking down space hogs, i.e., directories and files that consume large or excessive amounts of space on a hard disk drive (HDD) or other storage media.

A directory tree is a hierarchy of directories that consists of a single directory, called the parent directory or top level directory, and all levels of its subdirectories (i.e., directories within a directory). Any directory can be regarded as being the start of its own directory tree, at least if it contains subdirectories. Thus, a typical computer contains a large number of directory trees.

du is commonly employed by system administrators as a supplement to automated monitoring and notification programs that help prevent key directories and partitions (i.e., logically independent sections of a HDD) from becoming full. Full, or even nearly full, directories and partitions can cause a system to slow down, prevent users from logging in and even result in a system crash. Although visually identifying heavy consumers of disk space can be practical if there are relatively few users on a system, it is clearly not efficient for large systems with hundreds or thousands of users.

A minor limitation of du is the fact that the sizes of directories and files it reports are approximations, not exact numbers, and there is frequently a small discrepancy between these sizes and the sizes reported by other commands. However, this rarely detracts from its usefulness.

Also, du can only be used to estimate space consumption for directories and files for which the user has reading permission. Thus, an ordinary user would generally not be able to use du to determine space consumption for files or directories belonging to other users, including those belonging to the root account (i.e., the system administrator). However, as du is used mainly by system administrators, this is usually not a problem.

Syntax

The basic syntax for du is:

du [options] [directories and/or files]

The items in the square brackets are optional. When used with no options or arguments (i.e., names of directories or files), du lists the names and space consumption of each of the directories (including all levels of subdirectories) in the directory tree that begins with the current directory (i.e., the directory in which the user is currently working). The space consumption of any directory consists of the space occupied by all of the files in it and all of its subdirectories at all levels inclusive of all of the files in them. A final line at the end of the report gives the total space consumption for the directory tree.

du can provide information about any directory trees or files on the system whose names are given as arguments. For example, the following will report the names and sizes for each directory in the directory tree that begins with a directory named directory2 that resides in a directory named directory1, which, in turn, is located in the current directory:

du directory1/directory2

Likewise, the following will report the sizes of the two files named file1 and file2 that are located in the /sbin directory (which contains executable programs):

du /sbin/file1 /sbin/file2

du can accept any number of arguments, and they can be any combination of files and directories. When there are multiple arguments, no grand total is provided by default, although a total is still provided for each argument.

Options

As is the case with most commands on Linux and other Unix-like operating systems, du has a number of options, a few of which are commonly used. The options can vary somewhat according to the particular operating system and the version of du.

One of the most useful options is -h (i.e., human readable), which can make the output easier to read by displaying it in kilobytes (K), megabytes (M) and gigabytes (G) rather than just in the default kilobytes. Thus, the following command can be used to show the sizes of all the subdirectories in the current directory as well as the total size of the current directory, all formatted with the appropriate K, M or G:

du -h

The -s (for suppress or summarize) option tells du to report only the total disk space occupied by a directory tree and to suppress individual reports for its subdirectories. Thus, for example, the following would provide the total disk space occupied by the current directory in an easy-to-read format:

du -sh

The output is the same as the last line of a report issued by du with only the -h option.

The -a (i.e., all) option tells du to report not just the total disk usage for each directory at every level in a directory tree but also to report the space consumption for each individual file anywhere within the tree. Thus, for example, the following would list the name and size of every directory and file in the /etc directory (which contains system configuration files) for which the user has reading permission:

du -a /etc

A somewhat similar report is provided by using the star ( * ) wildcard, which will match any character or characters. For example, the following command would list the sizes of all directories that are in the tree that begins with the current directory:

du *

However, the only files listed are those in the the parent directory, not those in its subdirectories. Also, no total for the directory tree as a whole is provided.

The use of the -s option and the star wildcard together would cause du to report the names and sizes of only the files and directories contained directly in the top level directory itself (and to not list the names of any of its subdirectories and the files in them). The size of each listed directory is, of course, inclusive of all of its files and subdirectories (including all of the files in them). For example, such a report about the directory tree beginning with the current directory would be provided by the following:

du -hs *

The wildcard can also be used to filter the output to list only those items whose names begin with, contain or end with certain characters or sequences of characters. For example, the following would report the names and sizes of all of the directories and files in the current directory whose names begin with the letter s as well as the names and sizes of all levels of subdirectories of those directories regardless of what their names begin with:

du -h s*

The -c option can be added to provide a grand total for all of the files and directories that are listed. In the case of the above example, this would be

du -hc s*

As another example of the use of the wildcard, the following command would report the name and size of each gif (one of the two most popular image formats) file in the current directory as well as a total for all of the gifs:

du -hc *.gif

Another useful option is –max-depth=, which instructs du to list its subdirectories and their sizes to any desired level of depth (i.e., to any level of subdirectories) in a directory tree. For example, the following would cause du to list only the first tier (i.e., layer) of directories in the current directory and their sizes (inclusive of all of their contents, including those of their subdirectories):

du –max-depth=1

The total space consumption for the current directory tree will also be reported, and it will, of course, be the same regardless of the depth of the files listed.

Setting –max-depth= to zero tells du to not list any of the subdirectories within the selected directory, i.e., to list only report the size of the selected directory itself. The result is the same as using the -s option.

Using du With Filters

As is the case with other commands on Unix-like operating systems, du can be linked with pipes to filters to create powerful pipelines of commands. A filter is a (usually) small and specialized program that transforms data in some meaningful way.

For example, to arrange the output items according to size, du can be piped to the sort command, whose -n option tells it to list the output in numeric order with the smallest files first, as follows:

du | sort -n

As du will often generate more output than can fit on the monitor screen at one time, the output will fly by at high speed and be virtually unreadable. Fortunately, it is easy to display the output one screenful at a time by piping it to the less filter, for example,

du -h | less

The output of less can be advanced one screenful at a time by pressing the space bar, and it can be moved backward one screenful at a time by pressing the b key.

The output of du can likewise be piped to less after it has been passed through one or more other filters, for example,

du -h | sort -n | less

The grep filter can be used to search through du’s output for any desired string (i.e., sequence of characters). Thus, for example, the following will provide a list of the names and sizes of directories and files in the current directory that contain the word linux:

du -ah | grep linux

One way in which du can be used to produce a list of (mostly) directories and files in a directory tree that are consuming large amounts of disk space is to use grep to search for all the lines that contain the upper case letter M (i.e., for megabytes) or G (for gigabytes), such as

du -ah | grep M

The only problem with this approach is that it will also select directories and files that contain an upper case M or G in their names even if the file size is not measured in megabytes or gigabytes. (However, this problem could be overcome through the use of regular expressions, an advanced pattern matching technique).

Alternatives to du

There are several other ways of monitoring disk space consumption and reporting file sizes. Although very useful tools, they are generally not good substitutes for du.

Among them is the df command, which is likewise used by system administrators to monitor disk usage. However, unlike du, it can only show the space consumption on entire partitions, and it lacks du’s fine-grained ability to track the space usage of individual directories and files.

du is not designed to show the space consumption of partitions. The closest that it can come is to show the sizes of the first tier of directories in the root directory (i.e., the directory which contains all other directories and which is represented by a forward slash), several of which may be on their own partitions (depending on how the system has been set up). This is accomplished by becoming the root user and issuing the following command:

du -h –max-depth=1 /

The ls (i.e., list) command can provide the sizes of individual files by using its -s option, and its -h option (which is similar to du’s -h option) can be added to make the output easier to read. For example, the following would list the names and sizes of the files in the current directory:

ls -sh

Although the names of the first tier of directories within the current directory are also listed, the size data accompanying them does not represent their actual disk space consumption (i.e., inclusive of their contents). Nor does ls report the contents of any lower tiers of directories, unless such directories are specifically listed as arguments.

A convenient alternative for finding the sizes of files and directory trees when using a GUI (graphical user interface) is to click with the right mouse button on the icon (i.e., a small picture or symbol) for that item and then select Properties from the menu that appears. Although this is frequently sufficient, it does not provide the detailed control and reporting that du provides.

Courtesy – Linfo

Combining the Contents Multiple Files into a Single File Using Terminal

In this article, you will see how to combine the contents of multiple files into a single file using terminal. Lets consider a list of files with names “xaa”, “xab”, “xac” and “xad”. First lets see the contents of those files :

$ cat xaa

A$ cat xab

B$ cat xac

C$ cat xad

$

As you can see, those files contain the alphabets, A, B, C and the new line character respectively. Now if you want to concatenate the contents of those files, here is how you can do that.

$ cat x*>output.txt

Now this will concatenate the contents of those files and write it into a new file with name “output.txt”. Now you can see the contents of this new file to see the result.

$ cat output.txt

ABC

As you can see, the created file will have the content same as that of the concatenation of those original individual files.

Combining the Contents of Multiple Files Using Terminal

In this article, you will see how to combine the contents of multiple files using terminal. Lets consider a list of files with names “xaa”, “xab”, “xac” and “xad”. First lets see the contents of those files :

$ cat xaa

A$ cat xab

B$ cat xac

C$ cat xad

$

As you can see, those files contain the alphabets, A, B, C and the new line character respectively. Now if you want to concatenate the contents of those files, here is how you can do that.

$ cat x*

ABC

$

Now you will get the concatenated output.