Change Access Permissions with chmod

chmod changes the access permissions of the named files. Synopsis:
chmod [option]… {mode | --reference=ref_file} file…

Structure of File Mode Bits

The file mode bits have two parts: the file permission bits, which control ordinary access to the file, and special mode bits, which affect only some files.

There are three kinds of permissions that a user can have for a file:

  1. permission to read the file. For directories, this means permission to list the contents of the directory.
  2. permission to write to (change) the file. For directories, this means permission to create and remove files in the directory.
  3. permission to execute the file (run it as a program). For directories, this means permission to access files in the directory.

There are three categories of users who may have different permissions to perform any of the above operations on a file:

  1. the file’s owner;
  2. other users who are in the file’s group;
  3. everyone else.

Files are given an owner and group when they are created. Usually the owner is the current user and the group is the group of the directory the file is in, but this varies with the operating system, the file system the file is created on, and the way the file is created. You can change the owner and group of a file by using the chown and chgrp commands.

In addition to the three sets of three permissions listed above, the file mode bits have three special components, which affect only executable files (programs) and, on most systems, directories:

The set-user-ID bit (setuid bit): On execution, set the process’s effective user ID to that of the file. For directories on a few systems, give files created in the directory the same owner as the directory, no matter who creates them, and set the set-user-ID bit of newly-created subdirectories.

The set-group-ID bit (setgid bit): On execution, set the process’s effective group ID to that of the file. For directories on most systems, give files created in the directory the same group as the directory, no matter what group the user who creates them is in, and set the set-group-ID bit of newly-created subdirectories.

The restricted deletion flag or sticky bit: Prevent unprivileged users from removing or renaming a file in a directory unless they own the file or the directory; this is commonly found on world-writable directories like /tmp. For regular files on some older systems, save the program’s text image on the swap device so it will load more quickly when run, so that the image is “sticky”.

Setting Permissions

The basic symbolic operations on a file’s permissions are adding, removing, and setting the permission that certain users have to read, write, and execute or search the file. These operations have the following format:

users operation permissions

The spaces between the three parts above are shown for readability only; symbolic modes cannot contain spaces.

The users part tells which users’ access to the file is changed. It consists of one or more of the following letters. When more than one of these letters is given, the order that they are in does not matter.
u the user who owns the file;

gother users who are in the file’s group;

o all other users;

aall users; the same as ‘ugo’.

The operation part tells how to change the affected users’ access to the file, and is one of the following symbols:

+ to add the permissions to whatever permissions the users already have for the file;

- to remove the permissions from whatever permissions the users already have for the file;

= to make the permissions the only permissions that the users have for the file.

The permissions part tells what kind of access to the file should be changed; it is normally zero or more of the following letters. As with the users part, the order does not matter when more than one letter is given. Omitting the permissions part is useful only with the ‘=’ operation, where it gives the specified users no access at all to the file.

r the permission the users have to read the file;

w the permission the users have to write to the file;

x the permission the users have to execute the file, or search it if it is a directory.

For example, to give everyone permission to read and write a regular file, but not to execute it, use: a=rw

To remove write permission for all users other than the file’s owner, use: go-w

The above command does not affect the access that the owner of the file has to it, nor does it affect whether other users can read or execute the file.

To give everyone except a file’s owner no permission to do anything with that file, use the mode below. Other users could still remove the file, if they have write permission on the directory it is in. go=

Another way to specify the same thing is: og-rwx

chmod never changes the permissions of symbolic links, since the chmod system call cannot change their permissions. This is not a problem since the permissions of symbolic links are never used. However, for each symbolic link listed on the command line, chmod changes the permissions of the pointed-to file. In contrast, chmod ignores symbolic links encountered during recursive directory traversals.

Only a process whose effective user ID matches the user ID of the file, or a process with appropriate privileges, is permitted to change the file mode bits of a file.

A successful use of chmod clears the set-group-ID bit of a regular file if the file’s group ID does not match the user’s effective group ID or one of the user’s supplementary group IDs, unless the user has appropriate privileges. Additional restrictions may cause the set-user-ID and set-group-ID bits of mode or ref_file to be ignored. This behavior depends on the policy and functionality of the underlying chmod system call. When in doubt, check the underlying system behavior.

If used, mode specifies the new file mode bits. If you really want mode to have a leading ‘-’, you should use — first, e.g., ‘chmod -- -w file’. Typically, though, ‘chmod a-w file’ is preferable, and chmod -w file (without the –) complains if it behaves differently from what ‘chmod a-w file’ would do.

Let us take a look at options supported by chmod:

-c or --changes Verbosely describe the action for each file whose permissions actually changes.

-f or --silent or --quiet Do not print error messages about files whose permissions cannot be changed.

--preserve-rootFail upon any attempt to recursively change the root directory, /. Without --recursive, this option has no effect.

--no-preserve-root Cancel the effect of any preceding --preserve-root option.

-v or --verbose Verbosely describe the action or non-action taken for every file.

--reference=ref_file Change the mode of each file to be the same as that of ref_file. If ref_file is a symbolic link, do not use the mode of the symbolic link, but rather that of the file it refers to.

-R or --recursive Recursively change permissions of directories and their contents.

Examples:

# Change file permissions of FOO to be world readable
# and user writable, with no other permissions.
chmod 644 foo
chmod a=r,u+w foo

# Add user and group execute permissions to FOO.
chmod +110 file
chmod ug+x file

# Set file permissions of DIR and subsidiary files to
# be the umask default, assuming execute permissions for
# directories and for files already executable.
chmod -R a=,+rwX dir

Change Ownership with chown

On GNU/Linux every file is owned by a user and a group(consists of one or more than one user). There are 9 mode bits. rwxrwxrwx. rwx stands for read, write and execute. It is necessary for directories to have execute permission before a user can enter that. The first triplet of rwx is applicable for owner of the file, the second for group and the last applies to others. To control ownership and group of a file or directory you can use chown(change ownership) command. Synopsis:

chown [option]… {new-owner | --reference=ref_file} file…

If used, new-owner specifies the new owner and/or group as follows (with no embedded white space):

[owner] [ : [group] ]

Specifically:

owner If only an owner (a user name or numeric user ID) is given, that user is made the owner of each given file, and the files’ group is not changed. owner‘:’group

If the owner is followed by a colon and a group (a group name or numeric group ID), with no spaces between them, the group ownership of the files is changed as well (to group).

owner‘:’ If a colon but no group name follows owner, that user is made the owner of the files and the group of the files is changed to owner’s login group.

‘:’group If the colon and following group are given, but the owner is omitted, only the group of the files is changed; in this case, chown performs the same function as chgrp.

‘:’ If only a colon is given, or if new-owner is empty, neither the owner nor the group is changed.

If owner or group is intended to represent a numeric user or group ID, then you may specify it with a leading ‘+’.

So the command can be chwon owner or chown owner: or chown :group or chown :. Now let us look at most useful options supported by chown.

-c or --changes verbosely describes the action for each file whose ownership actually changes.

-f or --silent or --quiet Do not print error messages about files whose ownership cannot be changed.

--from=old-owner Change a file’s ownership only if it has current attributes specified by old-owner. old-owner has the same form as new-owner described above. This option is useful primarily from a security standpoint in that it narrows considerably the window of potential abuse. For example, to reflect a user ID numbering change for one user’s files without an option like this, root might run
find / -owner OLDUSER -print0 | xargs -0 chown -h NEWUSER
But that is dangerous because the interval between when the find tests the existing file’s owner and when the chown is actually run may be quite large. One way to narrow the gap would be to invoke chown for each file as it is found:
find / -owner OLDUSER -exec chown -h NEWUSER {} \;
But that is very slow if there are many affected files. With this option, it is safer (the gap is narrower still) though still not perfect:
chown -h -R --from=OLDUSER NEWUSER /

--dereference Do not act on symbolic links themselves but rather on what they point to. This is the default when not operating recursively.

Combining this dereferencing option with the --recursive option may create a security risk: During the traversal of the directory tree, an attacker may be able to introduce a symlink to an arbitrary target; when the tool reaches that, the operation will be performed on the target of that symlink, possibly allowing the attacker to escalate privileges.

-h or --no-dereference Act on symbolic links themselves instead of what they point to. This mode relies on the lchown system call. On systems that do not provide the lchown system call, chown fails when a file specified on the command line is a symbolic link. By default, no diagnostic is issued for symbolic links encountered during a recursive traversal, but see --verbose.

--preserve-root Fail upon any attempt to recursively change the root directory, /. Without --recursive, this option has no effect.

--no-preserve-root Cancel the effect of any preceding --preserve-root option.

--reference=ref_file Change the user and group of each file to be the same as those of ref_file. If ref_file is a symbolic link, do not use the user and group of the symbolic link, but rather those of the file it refers to.

-v or --verbose Output a diagnostic for every file processed. If a symbolic link is encountered during a recursive traversal on a system without the lchown system call, and --no-dereference is in effect, then issue a diagnostic saying neither the symbolic link nor its referent is being changed.

-R or --recursive Recursively change ownership of directories and their contents.

-H If --recursive (-R) is specified and a command line argument is a symbolic link to a directory, traverse it.

-L In a recursive traversal, traverse every symbolic link to a directory that is encountered.

Combining this dereferencing option with the --recursive option may create a security risk: During the traversal of the directory tree, an attacker may be able to introduce a symlink to an arbitrary target; when the tool reaches that, the operation will be performed on the target of that symlink, possibly allowing the attacker to escalate privileges.

-P Do not traverse any symbolic links. This is the default if none of -H, -L, or -P is specified.

Examples:

# Change the owner of /u to "root".
chown root /u

# Likewise, but also change its group to "staff".
chown root:staff /u

# Change the owner of /u and subfiles to "root".
chown -hR root /u

Print Newline, Word and Byte Counts with wc

wc counts the number of bytes, characters, whitespace-separated words, and newlines in each given file, or standard input if none are given or for a file of -. Synopsis:

wc [option]… [file]…

wc prints one line of counts for each file, and if the file was given as an argument, it prints the file name following the counts. If more than one file is given, wc prints a final line containing the cumulative counts, with the file name total. The counts are printed in this order: newlines, words, characters, bytes, maximum line length. Each count is printed right-justified in a field with at least one space between fields so that the numbers and file names normally line up nicely in columns. The width of the count fields varies depending on the inputs, so you should not depend on a particular field width. However, as a GNU extension, if only one count is printed, it is guaranteed to be printed without leading spaces.

By default, wc prints three counts: the newline, words, and byte counts. Options can specify that only certain counts be printed. Options do not undo others previously given, so

wc --bytes --words

prints both the byte counts and the word counts.

With the –max-line-length option, wc prints the length of the longest line per file, and if there is more than one file it prints the maximum (not the sum) of those lengths. The line lengths here are measured in screen columns, according to the current locale and assuming tab positions in every 8th column.

The program accepts the following options.

-c or --bytes prints only the byte counts.

-m or --chars prints only the character counts.

-w or --words prints only the word counts.

-l or --lines prints only newline counts.

-L or --max-line-length prints only the maximum display widths. Tabs are set at every 8th column. Display widths of wide characters are considered. Non-printable characters are given 0 width.

--files0-from=file disallows processing files named on the command line, and instead process those named in file file; each name being terminated by a zero byte (ASCII NUL). This is useful when the list of file names is so long that it may exceed a command line length limitation. In such cases, running wc via xargs is undesirable because it splits the list into pieces and makes wc print a total for each sublist rather than for the entire list. One way to produce a list of ASCII NUL terminated file names is with GNU find, using its -print0 predicate. If file is - then the ASCII NUL terminated file names are read from standard input.

For example, to find the length of the longest line in any .c or .h file in the current hierarchy, do this:

find . -name '*.[ch]' -print0 |  wc -L --files0-from=- | tail -n1

Consider we have a file test.txt with following content:
line 1
line 2

Invoking wc on it gives following output:

$ wc test.txt
2 4 14 test.txt

To do this for a directory you can execute it like find . - name "*"|xargs wc

Concatenate and Write Files in Reverse with tac Command

tac is reverse of cat command in functionality. tac copies each file (- means standard input), or standard input if none are given, to standard output, reversing the records (lines by default) in each separately. Synopsis:

tac [option]… [file]…

A sample run is shown below:

$ tac
gskjhsg
shgsgeg
skheghseg
skheghseg
shgsgeg
gskjhsg

Note that you need to press Ctrl+D before tac will reverse the standard input. Consider a file test.txt with two lines:

line 1
line 2

If we say tac test.txt then following will be the output:

line 2
line 1

-b or --before causes the separator to be attached to the beginning of the record that it precedes in the file.

-r or --regex treats the separator string as a regular expression.

-s separator or --separator=separator uses separator as the record separator, instead of newline. Note an empty separator is treated as a zero byte. I.e., input and output items are delimited with ASCII NUL.

To reverse a file character by charcter you can use: tac -r -s 'x\|[^x]'

Concatenate and write files with cat command

cat copies each file (‘-‘ means standard input), or standard input if none are given, to standard output. Synopsis:

cat [option] [file]…

If you simply use cat then it will echo whatever you type on terminal. To exit this you can use Ctrl +D(EOF character) or Ctrl + C(interrupt the process).

If one or more arguments(filenames) are passed then it will show the contents of these filenames on terminal or standard output which can be redirected to a file using > filename. Given below are some important options related with cat command.

-v or --show-nonprinting displays control characters except for LFD(line feed or enter key) and TAB using ‘^’ notation and precede characters that have the high bit set with ‘M-’.

-E or --show-ends displays a ‘$’ after the end of each line.

-T or --show-tabs displays TAB characters as ‘^I’.

-A or --show-all is equivalent to -vET.

-b or --number-nonblank numbers all nonempty output lines, starting with 1.

-n or --number numbers all output lines, starting with 1. This option is ignored if -b is in effect.

With this we have discussed most important options of cat command. For a full reference please see coreutils documentation for your operating system.

Changing directories with cd command

cd is the command used for changing directories on GNU/Linux. It is shorthand for change directory. Synopsis is give below:

cd [-L|[-P [-e]] [-@]] [dir]

cd .. will take you to parent directory. cd dirpath will change to the directory specified. dirpath can be an absolute path or a relative path. Absolute paths begin with a leaading /. cd - will take you to previous directory.

cd only changes the current directory to DIR. The default DIR is the value of the
HOME shell variable.

-L forces symbolic links to be followed.

-P makes cd use the physical directory structure without following symbolic links.

-e if the -P option is supplied, and the current working directory cannot be determined successfully, exit with a non-zero status

-@ on systems that support it, present a file with extended attributes as a directory containing the file attributes.

The default is to follow symbolic links, as if -L were specified. .. is processed by removing the immediately previous pathname component back to a slash or the beginning of DIR.

Removing(Deleting) Files and Directories with rm Command on GNU/Linux

rm which is shorthand for remove, removes files and directories. But by default, it does not delete directories. For full documentation please refer to coreutils documentation of your operating system. Given below is synopsis:

rm [option]… [file]…

Typical usage is rm filenames, where filenames can be one file or many files or a regular expression. To remove a directory you use rm -r dir which will cause recursive deletion of all files and directories specified.

If the -I or --interactive=once option is given, and there are more than three files or the -r, -R, or --recursive are given, then rm prompts the user for whether to proceed with the entire operation. If the response is not affirmative, the entire command is aborted.ttps://github.com/Unvanquished/PrototypeRendererIf the -I or --interactive=once option is given, and there are more than three files or the -r, -R, or --recursive are given, then rm prompts the user for whether to proceed with the entire operation. If the response is not affirmative, the entire command is aborted.

Otherwise, if a file is unwritable, standard input is a terminal, and the -f or --force option is not given, or the -i or --interactive=always option is given, rm prompts the user for whether to remove the file. If the response is not affirmative, the file is skipped.

Any attempt to remove a file whose last file name component is . or .. is rejected without any prompting, as mandated by POSIX.

Warning: If you use rm to remove a file, it is usually possible to recover the contents of that file. If you want more assurance that the contents are truly unrecoverable, consider using shred.

Removing a directory

-d or --dir removes a directory if the directory is empty. Use it like rm -d dir

Forcing deletion

-f or --force makes rm ignore nonexistent files and never prompts user. Ignores any previous -i or --interactive option. Use it like rm -f filename or rm -rf dirname.

With this we come to an end of most important usage options of rm command.

Moving(renaming) Files with mv Command on GNU/Linux

For a complete reference of mv command please refer to coreutils documentation installed on your system or refer to https://www.gnu.org/software/coreutils/manual/coreutils.html#mv-invocation. Here we will cover most important aspects of mv command with some examples.

mv command is used to move(cut and paste) or rename files. There is no separate command for renaming files on GNU/Linux. Given below is synopsis of mv command:

mv [option]… [-T] source dest
mv [option]… source… directory
mv [option]… -t directory source…

If two filenames are given then mv will either rename first file to second filename or overwrite second file. For example, consider we have a file called f in a directory. If we give a command mv f g whree g is absent then f will be renamed to g. However, if g is present then it will be overwritten. If last argument is a path then all other path arguments coming before that will be moved to last path. For example, mv f1 f2 dir dir1/ will move files f1 and f2 along with directory dir to dir1.

Warning: Avoid specifying a source name with a trailing slash, when it might be a symlink to a directory. Otherwise, mv may do something very surprising, since its behavior depends on the underlying rename system call. On a system with a modern Linux-based kernel, it fails with errno=ENOTDIR. However, on other systems (at least FreeBSD 6.1 and Solaris 10) it silently renames not the symlink but rather the directory referenced by the symlink.

Note: mv will only replace empty directories in the destination. Conflicting populated directories are skipped with a diagnostic.

Now let us see some of the most useful options of mv command.

Creating backup of existing files

You can pass -b or --backup=[method] options to mv to achieve this. Backup methods have been discussed in https://ashtavakra.org/blog/?p=47 with cp command.

Forcing mv

With -f or --force mv will not prompt the you before removing a destination file. If you specify more than one of the -i, -f, -n options, only the final one takes effect.

Interactive mv

With -i or --interactive mv will prompt whether to overwrite each existing destination file, regardless of its permissions. If the response is not affirmative, the file is skipped.

Not overwriting files in destination

With -n or --no-clobber mv will not overwrite existing files.

With this we come to end to most useful options of mv command. See you in next post.

Copying files in GNU/Linux with cp Command

GNU/Linux comes with a versatile cp command to copy files and folders. Typical invocation of cp involves a source and a target. Source can be file or directory and target can also be file or directory. However, if source is a directory then target must be a directory. A synopsis of cp command is given below:

cp [option]… [-T] source dest
cp [option]… source… directory
cp [option]… -t directory source…

If two filenames are given, cp copies first file to second. If source is a directory, -r or -R i.e. recursive copy or -a i.e. archive; must be supplied as an argument and target must be a directory. If source is a file but target is a directory, source file is copied to the target directory.

Consider we have two folders: one and two. one contains two files a and b while two is empty. Let us also assume that these two folders are in our home directory and our working directory is also home directory. To copy file a from one to two we can issue the command: cp one/a two. We can also supply full paths like cp ~/one/a ~/two where ~ signifies home directory. To copy entire folder one into two we can give following command: cp -r one two

Now we will see some of the most useful options of cp command which we can use to perform various different tasks while copying files and folders.

Archiving files and folders

You can use -a or --archive to achieve this. It preserves as much as possible of the structure and attributes of the original files in the copy (but do not attempt to preserve internal directory structure; i.e., ls -U may list the entries in a copied directory in a different order). It tries to preserve SELinux security context and extended attributes (xattr), but ignore any failure to do that and print no corresponding diagnostic. Equivalent to -dR --preserve=all with the reduced diagnostics.

Creating backups

You can use -b or --backup=[method] to create backups of files and folders. As mentioned in my previous post, backup files have ~ at the end of their names. method here can be one of none, off, numbered, t, existing, nil, simple and never. none and off mean never make backup, numbered and t mean make numbered backup, existing and nil mean make numbered backup of files that already have them and simple and never mean always make simple backups.

Consider we have two folders one and two. Both contain a filename called f. If we copy file like cp -b one/f two, then a backup of file will be created in folder two.

--copy-contents copies contents of special files like FIFOs as if they were regular files, if copying contents recursively. It is usually a mistake to use this option. It does not affect the copying of symbolic links.

Preserving file attributes

-p or --preserve=[attribute-list] where attribute list includes mode, ownership, timestamps, links, context(SELinux), xattr and all. Attribute list can be comma seprated list of one of more of above keywords.

Copying links

-d option should be used to copy symbolic links as links rather than copying what they are pointing to. It also preserves hard links between source files and copies.

Forcing copying

-f or --force forces copying. When copying without this option and an existing destination file cannot be opened for writing, the copy fails. However, with --force, when a destination file cannot be opened, cp then tries to recreate the file by first removing it. Note --force alone will not remove dangling symlinks. When this option is combined with --link (-l) or --symbolic-link (-s), the destination link is replaced, and unless --backup (-b) is also given there is no brief moment when the destination does not exist. This option is independent of the --interactive or -i option: neither cancels the effect of the other. This option is ignored when the --no-clobber or -n option is also used.

Copying contents of a symbolic link

-H options will make cp copy the contents a symbolic link is pointing to. However, if symbolic link points to a directory then further encountered symbolic link will be copied as it it.

Asking before overwriting or interactive copying

-i or --interactive option achieves this. It will make cp ask for confirmation before overwriting files in destination. It also overrides previous -n option.

Making links of non-directories

With -l or --link cp makes hard links instead of copies of non-directories.

Dereferencing symbolic links

With -L or --dereference cp will follow symbolic links when copying from them. With this option, cp cannot create a symbolic link. For example, a symlink (to regular file) in the source tree will be copied to a regular file in the destination tree.

Not overwriting files in target or destination

With -n or --no-clobber cp will not overwrite files and will be silent for the operation. This overrides any previous -i option. It is also mutually-exclusive with backup option.

Copying symbolic links as symbolic links

-P or --no-dereference will make cp copy symbolic links as symbolic links rather than copying files they are pointing to. This only affects symbolic links in the source. Symbolic links in destination are always followed, if possible.

With this we have covered most important options of cp command. For a complete reference please refer to coreutils documentation installed on your system or https://www.gnu.org/software/coreutils/manual/coreutils.html#cp-invocation

GNU/Linux ls command

The ls program lists information about files. On GNU/Linux everything is treated as a file. Even a directory is a file. While man page of ls, which you can see by invoking man ls on your terminal, summarizes the basic documentation the real documentation is in coreutils info package which you can read by invoking info coreutilson your terminal. Every command on GNU/Linux many take some options or arguments(also known as switches), sometimes mandatory and sometimes optional and at times there are sub-commands associated with each command. ls has no mandatory arguments. When invoked without an argument, ls prints files in the current directory. When you launch your terminal, it starts in your home directory. Full documentation of ls can be read at https://www.gnu.org/software/coreutils/manual/coreutils.html#ls-invocation. Quick help on any command is typically accessible using either -h or --help. Here, I am presenting most common options with examples. Say you are in home directory and you type ls then your output may be somewhat like below:

Typical ls command output

ls also accepts path as final argument. Consider we have an empty folder names 1 in our home directory. If we invoke ls like ls 1 from our home directory then it will have no output.

Hidden files and folders with ls

On GNU/Linux hidden files and folders start with a .(dot or period). To show these files you should use -a or –all arguments. Here, -a is short form of –all. If we perform ls -a on the empty folder 1 then it will show us two directories . and … Directory . always refers to current directory while directory .. refers to parent directory with one exception. In the root directory i.e. /, .. refers to same directory as . i.e. /. There is another switch for ls which can be used to see hidden files and folders. It is -A or --almost-all. The only difference is that the latter switch does not show . and .. directories.

Backup files

On GNU/Linux backup files have ~ appended to filename as last character. -B or --ignore-backups will not list these backup files.

Types of files

-l or --format=long or --format=verbose lists name of each file, print the file type, file mode bits, number of hard links, owner name, group name, size, and timestamp, normally the modification timestamp. It prints question marks for information that cannot be determined.

Consider our folder 1 has a file called f then ls -l if executed inside this directory will have following output:

Long listing with ls

Here, first character in the listing is -, which specifies file type. rw-rw-r-- permission bits, 1 is number of hard links, user shiv owns this file, owned by group shiv, sie is 0 bytes followed by modification timestamp and filename. We will learn about permission bits later let us first learn about various file types.

- refers to regular or ordinary file.

b refers to block special file typically used by storage devices.

c refers to character special file, for example sound card device.

C refers to high-performance or contiguous data file.

d refers to directory.

D door (Solaris 2.5 and up)

l refers to symbolic link. Think of these like short-cut files of Windows.

M off-line (“migrated”) file (Cray DMF)

n network special file (HP-UX)

p FIFO (named pipe)

P port (Solaris 10 and up)

s socket

? some other file type

The file mode bits listed are similar to symbolic mode specifications. But ls combines multiple bits into the third character of each set of permissions as follows:

s If the set-user-ID or set-group-ID bit and the corresponding executable bit are both set.

S If the set-user-ID or set-group-ID bit is set but the corresponding executable bit is not set.

t If the restricted deletion flag or sticky bit, and the other-executable bit, are both set. The restricted deletion flag is another name for the sticky bit.

T If the restricted deletion flag or sticky bit is set but the other-executable bit is not set.

x If the executable bit is set and none of the above apply.

- Otherwise.

Sorting listing of files

Most useful sorts are on the basis of time or size. The commands are ls -lt or ls -lS will sort according to time or size. If you combine like ls -lrt or ls -lrS then the sort will be reversed. You can also sort on the basis of ctime or mtime using -c and -u options.

Colored output

On modern operating systems usually this is enabled. However, if your ls does not give colored output then you can enable color with ls --color

Classification of files

-1 or --format=single-column list one file per line. This is the default for ls when standard output is not a terminal.

-F or --classify or --indicator-style=classifyappend a character to each file name indicating the file type. Also, for regular files that are executable, append *. The file type indicators are / for directories, @ for symbolic links, | for FIFOs, = for sockets, > for doors, and nothing for regular files. You can try ls -F /dev to see this in action.

Recursively listing a directory

You can use -R switch to recursively list contents of a directory. Beware though if your directory has large no. of files and folders inside it then it may take a long time to print all that on terminal.

With this we have discussed most important uses of ls command. For reference you can see the link given above of coreutils.