1 / 111

Dr. Jahangir Alam Linux Notes Part2

Dr. Jahangir Alam University Women's Polytechnic Linux Part 2

Download Presentation

Dr. Jahangir Alam Linux Notes Part2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Part 2: Working with Files & Folders Dr. Jahangir Alam Computer Engineering Section University Women’s Polytechnic Aligarh Muslim University, Aligarh November 5, 2020

  2. The ls Command ? ls command on Unix-like operating systems, lists information about files and directories. ? It lists files and directories, and their associated metadata, such as file size, ownership, and modification time. ? The general form of ls command is: $ls [Option...] [file | folder]... ? With no options, ls lists the files contained in the current direc- tory, sorting them alphabetically. ls: Important Options - ls offers a large number of options. Following table lists some important one: 2 of 111

  3. The ls Command (contd...) Option Description -a, --all -A, --almost-all -l --author --color -d, --directory -F, --classify list all files including hidden file starting with ’.’ Do not list implied "." and "..". list with long format - show permissions With -l, print the author of each file. colored list [=always/never/auto] list directories with ’ */’ Flags filenames by appending / to directories, * to executable files, @ to symbolic links etc. list file’s inode index number list long format including hidden files list long format with readable file size list with long format with file size list in reverse order list recursively directory tree list file size sort by file size sort by time & date List entries by columns (default with ls) List entries by lines instead by columns sort by extension name -i -la -lh -ls -r -R -s -S -t -C -x -X 3 of 111

  4. The ls Command (contd...) ls: Examples 1. Lists the total files in the directory and subdirectories, the names of the files in the current directory, their permissions, the number of subdirectories in directories listed, the size of the file, and the date of last modification. $ls -l Lists files with permissions, shows hidden files, displays them in a column format, and suppresses group information. $ls -alxo List the contents of your root directory. $ls / List the contents of your home directory no matter in which directory you are currently in. $ls˜ Display a list of directories in the current directory. $ls -d */ Display all directories with their contents in the current directory. $ls */ List all files containing the file extension .htm, .php, or .cgi. $ls *.{htm,php,cgi} Find the file last edited. $ls -t List files sorted by the time they were last modified in reverse order (most recently modified files last). $ls -ltr 2. 3. 4. 5. 6. 7. 8. 9. 4 of 111

  5. The ls Command (contd...) 10. List only files that begin with a vowel (a, e, i, o, or u). $ls [aeiou]* Display one file per line. $ls -1 Display File Size in Human Readable Format. $ls -lh (h stands for human readable form) and is used to display file size in easy to read format. i.e i.e M for MB, K for KB, G for GB. Display Files Recursively. $ls -R Display File Inode Number. $ls -i Visually classify of files With special characters $ls -F --help and --version have usual behaviour with ls. 11. 12. 13. 14. 15. 16. 5 of 111

  6. Shell Globbing: Brief Intro ? There may be a large number of files in a folder on a linux system. ? Iterating through a large list of files manually may be error-prone and not very efficient. ? Instead, we can take advantage of Bash wildcards which allow us to define patterns to match against filenames or strings. ? This process is known as globbing. ? Globbing is mainly used to match filenames or searching for content in a file. Globbing uses wildcard characters to create the pattern. ? Note that bash itself cannot recognize Regular Expressions (pat- tern matching). 6 of 111

  7. Shell Globbing: Brief Intro (contd...) ? Inside scripts, it is commands and utilities such as sed and awk, that interpret regular expressions. ? The most common wildcard characters that are used for creating globbing patterns are described below: ? Question Mark(?): ? ’?’ is used to match any single character. We can use ’?’ for multiple times for matching multiple characters. ? Suppose, you want to search those text filenames whose names are 4 characters long and extension is .txt. You can apply glob- bing pattern by using ‘?’ four times to do this task as follows: $ ls ????.txt 7 of 111

  8. Shell Globbing: Brief Intro (contd...) ? Now suppose, you want to search those document files whose names are 8 characters long, first 4 characters are f, o, o and t and extension is doc. Run the following command with globbing pattern to search the files. $ ls -l foot????.doc ? Suppose, you know the filename is ‘best’ and extension is 3 characters long, but don’t know the extension. Run the follow- ing command by using ‘?’ to search all files with the name ‘test’ having any extension of three characters long. $ ls -l best.??? ? Asterisk(*): 8 of 111

  9. Shell Globbing: Brief Intro (contd...) ? ‘*’ is used to match zero or more characters. If you have less information to search a file then you can use ‘*’ in globbing pattern. ? Suppose, you want to search all files with ‘pl’ extension. Run the following command using ‘*’ to do that task. $ ls -l *.pl ? Suppose, you know the starting character of the filename only which is ‘a’. Run the following command using ‘*’ to search all files of the current directory whose names are started with ‘a’. $ ls -l a*.* 9 of 111

  10. Shell Globbing: Brief Intro (contd...) ? Note: In Bash when the globstar option is enabled, two adjacent asterisk * used as a single pattern will match all files and zero or more directories and subdirectories. If followed by a slash /, it will match only directories and subdirectories. ? Square Bracket ([]): ? ‘[]’ is used to match the character from the range. ? Some of the mostly used range declarations are shown in the table on the next page. 10 of 111

  11. Shell Globbing: Brief Intro (contd...) Range Description [:upper:] or [A-Z] [:lower:] or [a-z] [:digit:] or [0-9] [:alpha:] or [a-zA-Z] [:alnum:] or [a-zA-Z0-9] All uppercase alphabets are defined by this range All lowercase alphabets are defined by this range All numeric digits are defined by this range All uppercase and lower alphabets are defined by this range All uppercase alphabets, lowercase alphabet and digits are defined by this range Any of the 128 ASCII characters. It is a bash specific character class. Only space and tab characters. Non-printable characters, i.e. control characters. Graphically printable characters, excluding space. Printable characters, including space. Punctuation characters. Any white-spaced character, including tabs, newline, carriage-return, and similar. Alphanumeric characters with underscore character _, meaning alnum + _. It is a bash specific character class. Hexadecimal digits. [:ascii:] [:blank:] [:cntrl:] [:graph:] [:print:] [:punct:] [:space:] [:word:] [:xdigit:] 11 of 111

  12. Shell Globbing: Brief Intro (contd...) ? Run the following command to search all files and folders whose name starts with a or b or c or d. $ ls -l [a-d]* ? Run the following command to search all files and folders whose name starts with A or B or C. $ ls -l [A-C]* ? Run the following command to search all files and folders whose name starts with any digit from 1 to 5. $ ls -l [1-5]* ? Run the following command to search all files and folders whose name starts with any alphanumeric character: 12 of 111

  13. Shell Globbing: Brief Intro (contd...) $ ls -l [[:alnum:]]* ? Run the following command to search all files and folders whose name starts with any digit: $ ls -l [[:digit:]]* ? Run the following command to search all files and folders whose name starts with any alpha character: $ ls -l [[:alpha:]]* Note: We shall once again get back to shell globbing in detail once we proceed to pattern matching. 13 of 111

  14. Symbolic Link ? A symbolic link, also referred to as a soft link or symlink may refer to any of the following: 1. It is a file that links to another file or directory using its path. Unlike a hard link, a symbolic link can link to any file or directory on any computer. In Unix like OS symbolic links are created with the ln command, and in Windows they are created using the mklink command. 2. Alternatively known as SYLK, a symbolic link is an ASCII formatted file with the extension .slk, used by some Microsoft applications. It can exchange data between some Microsoft applications such as Excel. ? Certainly, here we are interested in the first form of symbolic links. ? Following figure shows how symbolic links are created in Win- dows: 14 of 111

  15. Symbolic Link (contd...) Symbolic Links in Windows 15 of 111

  16. Symbolic Link (contd...) ? Once the symbolic link is created, using the dir command we can see the symbolic link in the directory listing. ? To get into the symbolic link directory, we would treat it like any other directory and use the cd command. ? More details on mklink command can be obtained from: https://www.computerhope.com/mklink.htm ? In linux symlink is created using the ln command. ? The general form of ln command is: $ ln -s {source-directory or file} {linkname} ? For example the following command creates a symlink named as mylink1 to the file sss in folder Desktop: 16 of 111

  17. Symbolic Link (contd...) $ln -s /home/jahangir/Desktop/sss mylink1 17 of 111

  18. The pwd Command ? pwd command on Unix-like operating systems, outputs the name of the current working directory. ? pwd stands for print working directory. ? It is a built-in shell utility which could be confirmed using the command type pwd. ? The general form of pwd command is: $pwd [Option] ? Two options available with pwd command are -L and -P. ? -L prints symbolic links, if any, while -P prints physical links. ? Execute the following commands: 18 of 111

  19. The pwd Command (contd...) $type pwd $pwd $pwd -L $pwd -P ? --help and --version have usual behaviour with pwd. 19 of 111

  20. The tree Command ? tree command on Unix-like operating systems, lists the contents of directories in a tree-like format. ? It can be used to understand/ structure your file system. ? tree is a recursive directory listing program that produces a depth-indented listing of files and outputs it to tty (terminal). ? (Note: It is colorized only if the LS_COLORS environment variable is set). ? With no arguments, tree lists the files in the current directory. ? When directory arguments are given, tree lists all the files and/or directories found in the given directories each in turn. ? tree then returns the total number of files and/or directories listed. 20 of 111

  21. The tree Command (contd...) ? By default, when a symbolic link is encountered, the path that the symbolic link refers to is printed after the name of the link in the format: name→real-path. ? The general form of tree command is: $tree [Options][directory] tree: Important Options - Like ls, tree also offers a large number of options. - Detailed listing of options is available at: https://www.geeksforgeeks.org/tree-command-unixlinux/ - Following table lists some important one: 21 of 111

  22. The tree Command (contd...) Option Description -a All files are printed. By default, tree does not print hidden files (those beginning with a dot ’.’). List directories only. Prints the full path prefix for each file. Tree will not print the indentation lines. Useful when used in conjunction with the -f option. List only those files that match the wild-card pattern* Do not list those files that match the wild-card pattern. Makes tree prune empty directories from the output, useful when used in conjunction with -P or -I. Do not descend directories that contain more than # entries. Prints (implies -D) and formats the date according to the format string which uses the strftime syntax (strftime( ) C function, part of the time.h library). Omits printing of the file and directory report at the end of the tree listing. Print the protections for each file (as per ls -l). Print the size of each file along with the name. Print the username, or UID # if no username is available, of the file. Print the group name, or GID # if no group name is available, of the file. Print the date of the last modification time for the file listed. Prints the inode number of the file or directory. Prints the device number to which the file or directory belongs. Appends a ’/’ for directories, a ’=’ for socket files, a ’*’ for executable files etc. as per ls -F Sort the output in reverse alphabetic order. Sort the output by last modification time instead of alphabetically. -d -f -i -P pattern -I pattern --prune --filelimit # --timefmt format --noreport -p -s -u -g -D --inodes --device -F -r -t 22 of 111

  23. The tree Command (contd...) tree: Examples 1. Display the contents of the current directory and subdirectories in a tree format. $tree 2. Show all files including hidden dot files $tree -a 3. Display the tree hierarchy of a directory. $tree -a ahmad 4. Displays a tree that lists all directories but only those files that begin with t. $tree -P ’t*’ 5. List a tree that shows the file permissions. $tree -p 6. Displays a tree containing all directories plus files that begin with t. Also display file permissions $tree -pP t* 7. Prints the device number to which the file or directory belongs. $tree --device 8. List the directory contents with the full path prefix for each sub-directory and file $tree -f 9. Print the output by last modification time instead of alphabetically. $tree -t 10. You can specify the maximum display depth of the directory tree using the -L option. For example, if you want a depth of 2, run the following command. $tree -L 2 23 of 111

  24. The tree Command (contd...) 11. We can also tell the tree to prune empty directories from the output by adding the –prune option, as shown below. $tree --prune Besides, to print the username of each file, use the -u option, and the -g option prints the group name. We can combine the -p, -u and -g options to do a long listing (somewhat similar to ls command) as shown below: $tree -pug We can also print the size of each file in bytes along with the name using the -s option. To print the size of each file but in a human-readable format, use the -h flag as shown below: $tree -s OR $tree -h To display the date of the last modification time for each sub-directory or file, use the -D options as follows: $tree -D Another useful option is --du, which reports the size of each sub-directory as the accumulation of sizes of all its files and subdirectories (and their files, and so on). $tree --du Last but not least, you can send or redirect the tree’s output to filename for later analysis using the -o option. $tree -o target_file Same thing could be done using: $tree > target_file 12. 13. 14. 15. 16. 17. 24 of 111

  25. Creating a file in Linux ? Following are various ways of creating a file in linux: 1. Using redirect operator (>) 2. Using cat command 3. Using echo command 4. Using printf command 5. Using a text editor 6. Using touch command ? Using redirect operator: ? The redirection symbol tells the system to output results into whatever we specify next. ? The target is usually a filename. we can use this symbol to create a new file as follows: $> myfile1.txt 25 of 111

  26. Creating a file in Linux (contd...) ? Above command creates an empty file named as ’myfile1.txt’. You can confirm using ls -l command. ? Using cat command: ? cat stands for ’catenate’. It is a multipurpose command. ? It is one of the most commonly-used commands in Unix-like operating systems. It can be used to: - Display files - Create new files - Copy files - Append the contents of a file to the end of another file i.e. combining them ? Display the contents of a file: 26 of 111

  27. Creating a file in Linux (contd...) ? The simplest way to use cat is to give it the name of a text file. It displays the contents of the text file on the screen. For instance: $cat myfile.txt OR $cat < myfile.txt ? ...will read the contents of mytext.txt and send them to standard output (your terminal screen). ? If we specify more than one file name, cat displays those files one after the other, catenating their contents to standard output. So the command: $cat myfile.txt myfile1.txt 27 of 111

  28. Creating a file in Linux (contd...) ? If a filename starts with dash ("-") use -- option with cat to dispaly file contents: $cat -- -filename ? Will print the contents of these two files as if they were a single file. ? Create new files: ? To create a file using cat, use the following command: $cat > myfile3.txt ? Press enter and typeset whatever you want. Save with Ctrl+d. ? Note the redirection operator. Without this the command dis- plays the contents of myfile3.txt on the screen. 28 of 111

  29. Creating a file in Linux (contd...) ? The redirection operator (>) tells the system to place the typed contents in the myfile3.txt file. ? If myfile3.txt does not exist, it will be created. ? Ifmyfile3.txt already exists, it will be overwritten and its previous contents will be lost, so be careful. ? Copy files: ? We can use cat to make copies of files. ? cat sends its output to stdout (standard output), which is usu- ally the terminal screen. ? However, we can redirect this output to a file using the shell redirection symbol ">". For instance the following command: 29 of 111

  30. Creating a file in Linux (contd...) $cat myfile3.txt > myfile4.txt OR $cat < myfile3.txt > myfile4.txt ? Sends (copies) contents of myfile3.txt to myfile4.txt. ? If myfile4.txt does not exist, it will be created. ? If myfile4.txt already exists, it will be overwritten and its previ- ous contents will be lost, so be careful. ? Similarly, we can catenate several files into one destination file. For instance: $cat mytext1.txt mytext2.txt > newfile.txt ? Append contents of one file to another: 30 of 111

  31. Creating a file in Linux (contd...) ? Instead of overwriting another file, we can also append a source text file to another using the double redirection or append op- erator (»). For instance the command: $cat mytext1.txt >> myfile2.txt ? will read the contents of myfile1.txt, and write them at the end of file myfile2.txt. ? If myfile2.txt. does not already exist, it will be created and the contents of myfile1.txt will be written to the new file. ? cat can also be used to append contents of multiple files to another file. cat: Important Options - cat offers several options. Following table lists some important one: 31 of 111

  32. Creating a file in Linux (contd...) Option Description -b, --number-nonblank Number non-empty output lines. This option over- rides -n. Display "$" at end of each line. Number all output lines. Suppress repeated empty output lines. Display TAB characters as∧I. Display a help message, and exit. Output version information, and exit. -E, --show-ends -n, --number -s, --squeeze-blank -T, --show-tabs --help --version - Examples: Run following commands: $cat -b myfile1.txt $cat -E myfile1.txt $cat -n myfile1.txt $cat -s myfile1.txt $cat -T myfile1.txt $cat -- help $cat -- version 32 of 111

  33. Creating a file in Linux (contd...) ? Using echo command: ? The echo command will duplicate whatever we give in the com- mand and put it into a file we specify. Run the following: $echo "The quick brown fox jumps over the lazy dog" > myfile5.txt ? Using printf command: ? The printf command works like the echo command, and it adds some formatting functionality. (However, formatting could also be added using echo command) ? To add two lines of text, enter: $printf "Hello linux.\n You are simple awesome.\n" > myfile6.txt ? Using a text editor: 33 of 111

  34. Creating a file in Linux (contd...) ? A large number of text editors are available for linux. They could be used to create files like ordinary text editors e.g. notepad, wordpad etc. ? Some text editors for linux are gedit, kwrite, pico, nano, vi, vim etc. ? Using touch command: ? On Unix-like operating systems, the touch command modifies file timestamps. ? If the file doesn’t exist, an empty file with that name is created. ? A timestamp is information associated with a file that identifies an important time in the file’s history. ? A file can have multiple timestamps, and some of them can be "forged" by setting them manually. 34 of 111

  35. Creating a file in Linux (contd...) ? In Linux, there are three timestamps associated with a file: Timestamp Type Description Abbreviation Access time Modification time The last time the file was read. The last time the contents of the file were modified. The last time the file’s metadata, called the Status, was changed. Status information in- cludes a file’s permissions and its timestamps. Every time anything happens to a file, at least one element of its status changes, and its ctime is set to the current system time. atime mtime Change Time ctime ? The atime and mtime are part of a file’s status metadata. Therefore, when we change the atime (-a) or mtime (-m) of a file, its ctime is automatically set to the current time. ? There is no way to manually set the ctime. 35 of 111

  36. Creating a file in Linux (contd...) ? A file’s atime or mtime can be set to the future or the past if the user owns the file. ? Windows operating system associates another time, named as Create time with the file. It should not be confused with Change time. ? Linux has nothing to do with create time. ? Difference between atime, mtime & ctime: ? Every Linux file has three timestamps: the access timestamp (atime), the modified timestamp (mtime), and the changed timestamp (ctime). 36 of 111

  37. Creating a file in Linux (contd...) ? The access timestamp is the last time a file was read. This means someone used a program to display the contents of the file or read some values from it. Nothing was edited or added to the file. The data was referenced but unchanged. ? A modified timestamp signifies the last time the contents of a file were modified. A program or process either edited or manipulated the file. “Modified” means something inside the file was amended or deleted, or new data was added. ? Changed timestamps aren’t referring to changes made to the contents of a file. Rather, it’s the time at which the metadata related to the file was changed. File permission changes, for example, will update the changed timestamp. ? Viewing Timestamps: 37 of 111

  38. Creating a file in Linux (contd...) ? Have a look at following table: S.No. Description Command 1. When we use the -l (long listing) option with ls, we can access the modified timestamp. If we want to see the access timestamp, use the -lu (access time) option with ls And finally, to see the change timestamp, we can use the -lc (change time) option with ls ls -l myfile.txt 2. ls -lu myfile.txt 3. ls -lc myfile.txt ? To see all timestamps simultaneously, use the stat command as follows: $stat myfile.txt ? Changing Timestamps: ? With no options, touch changes the atime, mtime, and ctime of file to the current system time e.g.: 38 of 111

  39. Creating a file in Linux (contd...) $touch myfile.txt ? If file doesn’t exist, it is created with current time as timestamps. touch: Important Options - touch offers several options. Following table lists some impor- tant one: 39 of 111

  40. Creating a file in Linux (contd...) Option Description -a -c, --no-create -d datestring, --date=datestring Set the access time only. Do not create files. Parse the date string datestring, and use it instead of current time. Strings valid to the date command are accepted by the -d option. In addition to having write access, the user must also own a file to set its times to the past or future. If file is a symbolic link and this option is specified, touch modifies the timestamp of the symlink, rather than its referenced file. If this option is not specified, touch will dereference symlinks before making modifications. This option implies -c: nothing is created if file does not exist. Set modification time only. Set the times of file to the times of file reffile instead of the current time. In addition to having write access, the user must also own a file to set its times to the past or future. Use the numeric timestamp instead of the current time. format of timestamp is [[CC]YY]MMDDhhmm[.ss]. In addition to having write access, the user must also own a file to set its times to the past or future. -h, –no-dereference -m -r=reffile, –reference=reffile -t timestamp The 40 of 111

  41. Creating a file in Linux (contd...) Option Description --time=timetype An alternate way to specify what type of time to set (as with -a and -m). The value of timetype must be one of the following: - atime, access, use: Set access time. (Equivalent to -a.) - mtime, modify: Set modification time. Equivalent to -m. This option can be specified twice nondestructively. For example, --time=atime --time=mtime is the same as -am. Display a help message, and exit. Display version information, and exit. --help --version touch: Examples - In following command: If file.txt exists, set its access, modi- fication, and change times (atime, mtime, and ctime) to the current system time. If file.txt doesn’t exist, create an empty file with that name. $touch file.txt 41 of 111

  42. Creating a file in Linux (contd...) - The following commands set file times to the current system time. If file does not exist, does nothing. $touch -c file.txt OR $touch -h file.txt - The following command changes the atime of file.txt. mtime is not changed. The ctime is set to the current system time. If file.txt does not exist, it is created. The $touch -a file.txt - Change the access and modification times of file2.txt to match the times of file1.txt. The ctime will be set to the current system time. If file2.txt does not exist, it is not created. $touch -cr file1.txt file2.txt 42 of 111

  43. Creating a file in Linux (contd...) - The following command changes the atime and mtime of file2.txt to match the atime and mtime of a.txt. If file2.txt doesn’t exist, do nothing. If file2.txt is a symlink, set the times of the symlink. Do not touch the referenced file. $touch -ahmcr file1.txt file2.txt - The above command could also be stated as follows: $touch –time=atime –no-dereference reference=file1.txt file2.txt - The following command sets the atime and mtime of file1.txt to 1:02 AM, today. –time=mtime –no-create – $touch -d "01:02" file1.txt - Above command can also be stated as: $touch -d "1:2" file1.txt 43 of 111

  44. Creating a file in Linux (contd...) - The following command sets the mtime of file1.txt to September 1, 1927, 11:58 PM and 59 seconds. The ctime is set to the current system time. The atime is not changed. $touch -md "Sep 1 1927 23:58:59" file1.txt - The following command sets the mtime of file1.txt to September 1, 1927, 11:58 PM and 59 seconds. The ctime is set to the current system time. The atime is not changed. $touch –time=01020304 file1.txt - The following command sets the atime and mtime of file1.txt to June 7, 2050, 4:05 AM. The ctime is set to the current system time. $touch -t 5006070405 file1.txt 44 of 111

  45. Creating a file in Linux (contd...) - Following command is same as the previous command, but ex- plicitly specifying the century (20). $touch -t 205006070405 file1.txt - The following command sets the atime of file1.txt to March 4, 1950, 5:06 AM and 59 seconds. The ctime is set to the current system time. The mtime is not changed. $touch -at 195003040506.59 file1.txt - As pointed out earlier ctime of a file can’t be set to past or future. Any change in file metadata, sets the ctime to current system time. One way of setting ctime to current system time is to alter file permissions using chmod. ? An Important Note: 45 of 111

  46. Creating a file in Linux (contd...) ? One of the things which confuses many Linux users is why the access time attribute of a file does not change, although the file has been clearly accessed a number of times recently. ? The answer to this question lies in the mount option used by Linux while mounting the filesystem. ? The Linux Kernel starting from version 2.6.30 switched to using the relatime option by default during file system mount. ? This option causes the atime attribute to update only if the previous atime is older than mtime or ctime, or the previous atime is over 24 hours old. ? If the Kernel was to update the atime everytime a file was accessed that would be a big performance killer for disks. Specially in servers with lots of files which are accessed frequently, updating the atime attribute everytime a file is accessed would be a huge I/O burden, that is why the Kernel now defaults to relatime. ? If you want to have the original atime functionality you must use the strictatime option. In that case use the following command: $sudo mount -o remount,strictatime /home ? Above command restores the original atime functionality for the current session. 46 of 111

  47. The file Command ? On Unix-like operating systems, the file command reports a file’s type. ? The file command attempts to classify each filesystem object (i.e., file, directory or link) that is provided to it as an argument (i.e., input). ? Thus, it can usually provide immediate information as to whether some specified object is, for example, a GIF image file, a direc- tory, a GNU tar archive, ASCII English text, a symbolic link, an HTML document, an empty file, bzip2 compressed data, an executable, etc. ? The file command tests each argument in an attempt to classify it. There are three tests performed in this order: filesystem tests, magic tests, and language tests. 47 of 111

  48. The file Command (contd...) ? The first test that succeeds causes the file type to be printed. ? The first is a filesystem test, which uses the stat system call to obtain information from the object’s inode (which contains information about a file). ? A system call is a request in a Unix-like operating system for a service performed by the kernel (i.e., the core of the operating system). ? The second test checks to see if there is a magic number, which is a number embedded at or near the beginning of many types of files that indicates the file format (i.e., the type of file). 48 of 111

  49. The file Command (contd...) ? In the event that the first two tests fail to determine the type of a file, language tests are employed to determine if it is plain text (i.e., composed entirely of human-readable characters), and, if so, what type of plain text, such as HTML (hypertext markup language) or source code (i.e., the original version of a program as written by a human). ? In this situation, file also attempts to determine the natural language (e.g., English, Turkish or Japanese) that is used in the file. ? The general form of file command is: $file [Option(s)] object_name(s) 49 of 111

  50. The file Command (contd...) file: Important Options - file offers several options. Following table lists some important one: Option Description -b, --brief -C, --compile Do not prepend (add) file names to output lines (brief mode). Write a magic.mgc output file that contains a pre-parsed version of the magic file or directory. Exclude the test named in testname from the list of tests made to determine the file type. Valid test names are: apptype -EMX application type (only on EMX), ascii - Various types of text files (this test will try to guess the text encoding, irrespective of the setting of the ‘encoding’ option), encoding - Different text encodings for soft magic tests, tokens -Ignored for backward compatibility, cdf - Prints details of Compound Document Files, compress- Checks for, and looks inside, compressed files, elf - Prints ELF file details, soft - Consults magic files, tar - Examines tar files. Use the specified string separator as the separator between the file name and the file result returned. Defaults to ‘:’. Read the names of the files to be examined from namefile (one per line) before the argument list. Either namefile or at least one file name argument must be present. option causes symlinks not to be followed (on systems that support sym- bolic links). This option is the POSIXLY_CORRECT is not defined. -e, testname --exclude -F, separator -f, namefile --separator --files-from -h, dereference --no- default if the environment variable 50 of 111

More Related