0% found this document useful (0 votes)
5 views34 pages

Linux Code.software

The document provides a comprehensive overview of various Linux commands, including 'cat', 'pwd', 'ls', 'cd', 'rm', 'mkdir', and 'cp', detailing their syntax, options, and descriptions. Each command is explained with examples and options that modify their behavior. This serves as a beginner's guide to understanding and using basic Linux commands effectively.

Uploaded by

dasshubham505
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views34 pages

Linux Code.software

The document provides a comprehensive overview of various Linux commands, including 'cat', 'pwd', 'ls', 'cd', 'rm', 'mkdir', and 'cp', detailing their syntax, options, and descriptions. Each command is explained with examples and options that modify their behavior. This serves as a beginner's guide to understanding and using basic Linux commands effectively.

Uploaded by

dasshubham505
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Linux for Beginners code and command

Command Named
Every Linux command has 3 part :

Options

Argument

Cat : It is a command , for which we can display any text command.

if we use , Cat -n abc.txt

option Argument

NAME

CAT - concatenate files and print on the standard output


SYNOPSIS

cat [OPTION]... [FILE]...

DESCRIPTION

Concatenate FILE(s) to standard output.

With no FILE, or when FILE is -, read standard input.

-A, --show-all equivalent to -vET

-b, --number-nonblank number nonempty output lines, overrides -n

-e equivalent to -vE

-E, --show-ends display $ at end of each line

-n, --number number all output lines

-s, --squeeze-blank suppress repeated empty output lines

-t equivalent to -vT

-T, --show-tabs

-u (ignored)

-v, --show-nonprinting
use ^ and M- notation, except for LFD and TAB

--help display this help and exit

--version
output version information and exit

EXAMPLES
cat f - g
Output f's contents, then standard input, then g's contents.

cat Copy standard input to standard output.


NAME

pwd - print name of current/working directory

SYNOPSIS

pwd [OPTION]...

DESCRIPTION

Print the full filename of the current working directory.

-L, --logical
use PWD from environment, even if it contains symlinks

-P, --physical
avoid all symlinks

--help display this help and exit

--version
output version information and exit

If no option is specified, -P is assumed.

NOTE: your shell may have its own version of pwd, which usually supersedes
the version described here. Please refer to your
shell's documentation for details about the options it supports.
NAME

ls - list directory contents

SYNOPSIS

ls [OPTION]... [FILE]...

DESCRIPTION

List information about the FILEs (the current directory by default). Sort entries
alphabetically if

none of -cftuvSUX nor --sort is specified.

Mandatory arguments to long options are mandatory for short options too.

-a, --all
do not ignore entries starting with .

-A, --almost-all
do not list implied . and ..

--author
with -l, print the author of each file

-b, --escape
print C-style escapes for nongraphic characters

--block-size=SIZE
with -l, scale sizes by SIZE when printing them; e.g., '--block-size=M'; see
SIZE format below

-B, --ignore-backups
do not list implied entries ending with ~

-c with -lt: sort by, and show, ctime (time of last change of file status
information); with -l:
show ctime and sort by name; otherwise: sort by ctime, newest first

-C list entries by columns

--color[=WHEN]
color the output WHEN; more info below
-d, --directory
list directories themselves, not their contents

-D, --dired
generate output designed for Emacs' dired mode

-f list all entries in directory order

-F, --classify[=WHEN]
append indicator (one of */=>@|) to entries WHEN

--file-type
likewise, except do not append '*'

--format=WORD
--full-time
like -l --time-style=full-iso

-g like -l, but do not list owner

--group-directories-first
group directories before files; can be augmented with a --sort option,
but any use of
--sort=none (-U) disables grouping

-G, --no-group
in a long listing, don't print group names

-h, --human-readable
with -l and -s, print sizes like 1K 234M 2G etc.

--si likewise, but use powers of 1000 not 1024

-H, --dereference-command-line
follow symbolic links listed on the command line

--dereference-command-line-symlink-to-dir
follow each command line symbolic link that points to a directory

--hide=PATTERN
do not list implied entries matching shell PATTERN (overridden by -a or -A)

--hyperlink[=WHEN]
hyperlink file names WHEN
--indicator-style=WORD
append indicator with style WORD to entry names: none (default), slash
(-p), file-type
(--file-type), classify (-F)

-i, --inode
print the index number of each file

-I, --ignore=PATTERN
do not list implied entries matching shell PATTERN

-k, --kibibytes
default to 1024-byte blocks for file system usage; used only with -s and per
directory totals

-l use a long listing format

-L, --dereference
when showing file information for a symbolic link, show information for the
file the link ref‐
erences rather than for the link itself

-m fill width with a comma separated list of entries

-n, --numeric-uid-gid
like -l, but list numeric user and group IDs

-N, --literal
print entry names without quoting

-o like -l, but do not list group information

-p, --indicator-style=slash
append / indicator to directories

-q, --hide-control-chars
print ? instead of nongraphic characters

--show-control-chars
show nongraphic characters as-is (the default, unless program is 'ls' and
output is a terminal)

-Q, --quote-name
enclose entry names in double quotes

--quoting-style=WORD
use quoting style WORD for entry names: literal, locale, shell, shell-
always, shell-escape,
shell-escape-always, c, escape (overrides QUOTING_STYLE environment
variable)

-r, --reverse
reverse order while sorting

-R, --recursive
list subdirectories recursively

-s, --size
print the allocated size of each file, in blocks
-s, --size
print the allocated size of each file, in blocks

-S sort by file size, largest first

--sort=WORD
sort by WORD instead of name: none (-U), size (-S), time (-t), version (-v),
extension (-X),
width

--time=WORD
select which timestamp used to display or sort; access time (-u): atime,
access, use; metadata
change time (-c): ctime, status; modified time (default): mtime,
modification; birth time:
birth, creation;

with -l, WORD determines which time to show; with --sort=time, sort by
WORD (newest first)

--time-style=TIME_STYLE
time/date format with -l; see TIME_STYLE below

-t sort by time, newest first; see --time

-T, --tabsize=COLS
assume tab stops at each COLS instead of 8
-u with -lt: sort by, and show, access time; with -l: show access time and sort
by name; other‐
wise: sort by access time, newest first

-v natural sort of (version) numbers within text

-w, --width=COLS
set output width to COLS. 0 means no limit

-x list entries by lines instead of by columns

-X sort alphabetically by entry extension

-Z, --context
print any security context of each file

--zero end each output line with NUL, not newline

-1 list one file per line

--help display this help and exit

--version
output version information and exit

The SIZE argument is an integer and optional unit (example: 10K is


10*1024). Units are
K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary
prefixes can be used, too:
KiB=K, MiB=M, and so on.

The TIME_STYLE argument can be full-iso, long-iso, iso, locale, or


+FORMAT. FORMAT is interpreted
like in date(1). If FORMAT is FORMAT1<newline>FORMAT2, then
FORMAT1 applies to non-recent files and FORMAT2 to recent files. TIME_STYLE
prefixed with 'posix-' takes effect only outside the POSIX lo‐
cale. Also the TIME_STYLE environment variable sets the default style to use.

The WHEN argument defaults to 'always' and can also be 'auto' or 'never'.

Using color to distinguish file types is disabled both by default and with --
color=never. With
--color=auto, ls emits color codes only when standard output is connected to a
terminal. The LS_COL‐
ORS environment variable can change the settings. Use the dircolors(1)
command to set it.

Exit status:
0 if OK,

1 if minor problems (e.g., cannot access subdirectory),

2 if serious trouble (e.g., cannot access command-line argument).

Cd : Command Directery . Cd always takes you to the position . As it is a chained


Directery .

In linux all the file is located as a tree and “ / “ is here and files are here node.
“ ~ “ is actually represent home.

NAME
rm - remove files or directories

SYNOPSIS
rm [OPTION]... [FILE]...

DESCRIPTION
This manual page documents the GNU version of rm. rm removes each
specified file. By default, it does not remove directo‐
ries.

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.

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 affirma‐
tive, the file is skipped.

OPTIONS
Remove (unlink) the FILE(s).

-f, --force
ignore nonexistent files and arguments, never prompt

-i prompt before every removal

-I prompt once before removing more than three files, or when removing
recursively; less intrusive than -i, while still
giving protection against most mistakes

--interactive[=WHEN]
prompt according to WHEN: never, once (-I), or always (-i); without
WHEN, prompt always

--one-file-system
when removing a hierarchy recursively, skip any directory that is on a file
system different from that of the corre‐
sponding command line argument

--no-preserve-root
do not treat '/' specially

--preserve-root[=all]
do not remove '/' (default); with 'all', reject any command line argument on a
separate device from its parent

-r, -R, --recursive


remove directories and their contents recursively

-d, --dir
remove empty directories

-v, --verbose
explain what is being done

--help display this help and exit

--version
output version information and exit

By default, rm does not remove directories. Use the --recursive (-r or -R)
option to remove each listed directory, too,
along with all of its contents.

To remove a file whose name starts with a '-', for example '-foo', use one of these
commands:

rm -- -foo
rm ./-foo

Note : that if you use rm to remove a file, it might be possible to recover some of
its contents, given sufficient expertise
and/or time. For greater assurance that the contents are truly unrecoverable,
consider using shred(1).

NAME

mkdir - make directories


SYNOPSIS
mkdir [OPTION]... DIRECTORY...

DESCRIPTION
Create the DIRECTORY(ies), if they do not already exist.

Mandatory arguments to long options are mandatory for short options too.

-m, --mode=MODE
set file mode (as in chmod), not a=rwx - umask

-p, --parents
no error if existing, make parent directories as needed, with their file modes
unaffected by any -m option.

-v, --verbose
print a message for each created directory

-Z set SELinux security context of each created directory to the default type

--context[=CTX]
like -Z, or if CTX is specified then set the SELinux or SMACK security
context to CTX

--help display this help and exit

--version
output version information and exit.

NAME
cp - copy files and directories

SYNOPSIS
cp [OPTION]... [-T] SOURCE DEST
cp [OPTION]... SOURCE... DIRECTORY
cp [OPTION]... -t DIRECTORY SOURCE...

DESCRIPTION
Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.

Mandatory arguments to long options are mandatory for short options too.

-a, --archive
same as -dR --preserve=all

--attributes-only
don't copy the file data, just the attributes

--backup[=CONTROL]
make a backup of each existing destination file

-b like --backup but does not accept an argument

--copy-contents
copy contents of special files when recursive

-d same as --no-dereference --preserve=links

--debug
explain how a file is copied. Implies -v

-f, --force
if an existing destination file cannot be opened, remove it and try again
(this option is ignored when the -n option
is also used)

-i, --interactive
prompt before overwrite (overrides a previous -n option)

-H follow command-line symbolic links in SOURCE

-l, --link
hard link files instead of copying

-L, --dereference
always follow symbolic links in SOURCE

-n, --no-clobber
do not overwrite an existing file and do not fail (overrides a -u or previous -i
option). See also --update; equiva‐
lent to --update=none.

-P, --no-dereference
never follow symbolic links in SOURCE

-p same as --preserve=mode,ownership,timestamps

--preserve[=ATTR_LIST]
preserve the specified attributes

--no-preserve=ATTR_LIST
don't preserve the specified attributes

--parents use full source file name under DIRECTORY

-R, -r, --recursive


copy directories recursively

--reflink[=WHEN]
control clone/CoW copies. See below

--remove-destination
remove each existing destination file before attempting to open it (contrast
with --force)

--sparse=WHEN
control creation of sparse files. See below

--strip-trailing-slashes
remove any trailing slashes from each SOURCE argument

-s, --symbolic-link
make symbolic links instead of copying

-S, --suffix=SUFFIX
override the usual backup suffix

-t, --target-directory=DIRECTORY
copy all SOURCE arguments into DIRECTORY

-T, --no-target-directory
treat DEST as a normal file
--update[=UPDATE]
control which existing files are updated; UPDATE={all,none,older(default)}.
See below

-u equivalent to --update[=older]

-v, --verbose
explain what is being done

-x, --one-file-system
stay on this file system

-Z set SELinux security context of destination file to default type

--context[=CTX]
like -Z, or if CTX is specified then set the SELinux or SMACK security
context to CTX

--help display this help and exit

--version
output version information and exit

ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for


permissions (including any ACL and xattr permis‐
sions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for
hard links, 'context' for security con‐
text, 'xattr' for extended attributes, and 'all' for all attributes.

NAME
mv - move (rename) files

SYNOPSIS
mv [OPTION]... [-T] SOURCE DEST
mv [OPTION]... SOURCE... DIRECTORY
mv [OPTION]... -t DIRECTORY SOURCE...

DESCRIPTION
Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.

Mandatory arguments to long options are mandatory for short options too.
--backup[=CONTROL]
make a backup of each existing destination file

-b like --backup but does not accept an argument

--debug
explain how a file is copied. Implies -v

-f, --force
do not prompt before overwriting

-i, --interactive
prompt before overwrite

-n, --no-clobber
do not overwrite an existing file

If you specify more than one of -i, -f, -n, only the final one takes effect.

--no-copy
do not copy if renaming fails

--strip-trailing-slashes
remove any trailing slashes from each SOURCE argument

-S, --suffix=SUFFIX
override the usual backup suffix

-t, --target-directory=DIRECTORY
move all SOURCE arguments into DIRECTORY

-T, --no-target-directory
treat DEST as a normal file

--update[=UPDATE]
control which existing files are updated; UPDATE={all,none,older(default)}.
See below

-u equivalent to --update[=older]

-v, --verbose
explain what is being done

-Z, --context
set SELinux security context of destination file to default type
--help display this help and exit

--version
output version information and exit

UPDATE controls which existing files in the destination are replaced. 'all' is the
default operation when an --update option
is not specified, and results in all existing files in the destination being replaced.
'none' is similar to the --no-clobber
option, in that no files in the destination are replaced, but also skipped files do
not induce a failure. 'older' is the de‐
fault operation when --update is specified, and results in files being replaced
if they're older than the corresponding
source file.

The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.


The version control method may be selected via
the --backup option or through the VERSION_CONTROL environment variable.
Here are the values:

none, off
never make backups (even if --backup is given)

numbered, t
make numbered backups

existing, nil
numbered if numbered backups exist, simple otherwise

simple, never
always make simple backups

NAME
date - print or set the system date and time

SYNOPSIS
date [OPTION]... [+FORMAT]
date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]

DESCRIPTION
Display date and time in the given FORMAT. With -s, or with
[MMDDhhmm[[CC]YY][.ss]], set the date and time.

Mandatory arguments to long options are mandatory for short options too.

-d, --date=STRING
display time described by STRING, not 'now'

--debug
annotate the parsed date, and warn about questionable usage to stderr

-f, --file=DATEFILE
like --date; once for each line of DATEFILE

-I[FMT], --iso-8601[=FMT]
output date/time in ISO 8601 format. FMT='date' for date only (the
default), 'hours', 'minutes', 'seconds', or 'ns'
for date and time to the indicated precision. Example: 2006-08-
14T02:34:56-06:00

--resolution
output the available resolution of timestamps Example: 0.000000001

-R, --rfc-email
output date and time in RFC 5322 format. Example: Mon, 14 Aug 2006
02:34:56 -0600

--rfc-3339=FMT
output date/time in RFC 3339 format. FMT='date', 'seconds', or 'ns' for date
and time to the indicated precision.
Example: 2006-08-14 02:34:56-06:00

-r, --reference=FILE
display the last modification time of FILE

-s, --set=STRING
set time described by STRING

-u, --utc, --universal


print or set Coordinated Universal Time (UTC)

--help display this help and exit

--version
output version information and exit
All options that specify the date to display are mutually exclusive. I.e.: --date, --
file, --reference, --resolution.

FORMAT controls the output. Interpreted sequences are:

%% a literal %

%a locale's abbreviated weekday name (e.g., Sun)

%A locale's full weekday name (e.g., Sunday)

%b locale's abbreviated month name (e.g., Jan)

%B locale's full month name (e.g., January)

%c locale's date and time (e.g., Thu Mar 3 23:05:25 2005)

%C century; like %Y, except omit last two digits (e.g., 20)

%d day of month (e.g., 01)

%D date; same as %m/%d/%y

%e day of month, space padded; same as %_d

%F full date; like %+4Y-%m-%d

%g last two digits of year of ISO week number (see %G)

%G year of ISO week number (see %V); normally useful only with %V

%h same as %b

%H hour (00..23)

%I hour (01..12)

%j day of year (001..366)

%k hour, space padded ( 0..23); same as %_H

%l hour, space padded ( 1..12); same as %_I


%m month (01..12)

%M minute (00..59)

%n a newline

%N nanoseconds (000000000..999999999)

%p locale's equivalent of either AM or PM; blank if not known

%P like %p, but lower case

%q quarter of year (1..4)

%r locale's 12-hour clock time (e.g., 11:11:04 PM)

%R 24-hour hour and minute; same as %H:%M

%s seconds since the Epoch (1970-01-01 00:00 UTC)

%S second (00..60)

%t a tab

%T time; same as %H:%M:%S

%u day of week (1..7); 1 is Monday

%U week number of year, with Sunday as first day of week (00..53)

%V ISO week number, with Monday as first day of week (01..53)

%w day of week (0..6); 0 is Sunday

%W week number of year, with Monday as first day of week (00..53)


%x locale's date representation (e.g., 12/31/99)

%X locale's time representation (e.g., 23:13:48)

%y last two digits of year (00..99)

%Y year

%z +hhmm numeric time zone (e.g., -0400)


%:z +hh:mm numeric time zone (e.g., -04:00)

%::z +hh:mm:ss numeric time zone (e.g., -04:00:00)

%:::z numeric time zone with : to necessary precision (e.g., -04, +05:30)

%Z alphabetic time zone abbreviation (e.g., EDT)

By default, date pads numeric fields with zeroes. The following optional flags
may follow '%':

- (hyphen) do not pad the field

_ (underscore) pad with spaces

0 (zero) pad with zeros

+ pad with zeros, and put '+' before future years with >4 digits

^ use upper case if possible

# use opposite case if possible

After any flags comes an optional field width, as a decimal number; then an
optional modifier, which is either E to use the
locale's alternate representations if available, or O to use the locale's alternate
numeric symbols if available.

EXAMPLES
Convert seconds since the Epoch (1970-01-01 UTC) to a date

$ date --date='@2147483647'

Show the time on the west coast of the US (use tzselect(1) to find TZ)

$ TZ='America/Los_Angeles' date

Show the local time for 9AM next Friday on the west coast of the US

$ date --date='TZ="America/Los_Angeles" 09:00 next Fri'

DATE STRING
The --date=STRING is a mostly free format human readable date string such as
"Sun, 29 Feb 2004 16:21:42 -0800" or "2004-02-29
16:21:42" or even "next Thursday". A date string may contain items indicating
calendar date, time of day, time zone, day of
week, relative time, relative date, and numbers. An empty string indicates the
beginning of the day. The date string format
is more complex than is easily documented here but is fully described in the info
documentation.

NAME
cal, ncal — displays a calendar and the date of Easter

SYNOPSIS
cal [-3hjy] [-A number] [-B number] [[month] year]
cal [-3hj] [-A number] [-B number] -m month [year]
ncal [-3bhjJpwySM] [-A number] [-B number] [-W number] [-s country_code]
[[month] year]
ncal [-Jeo] [-A number] [-B number] [year]
ncal [-CN] [-H yyyy-mm-dd] [-d yyyy-mm]

DESCRIPTION
The cal utility displays a simple calendar in traditional format and ncal offers an
alternative layout, more options and the
date of Easter. The new format is a little cramped but it makes a year fit on a
25x80 terminal. If arguments are not speci‐
fied, the current month is displayed.

The options are as follows:


-h Turns off highlighting of today.

-J Display Julian Calendar, if combined with the -o option, display date of


Orthodox Easter according to the Julian Cal‐
endar.

-e Display date of Easter (for western churches).

-j Display Julian days (days one-based, numbered from January 1).

-m month
Display the specified month. If month is specified as a decimal number,
appending ‘f’ or ‘p’ displays the same month
of the following or previous year respectively.

-o Display date of Orthodox Easter (Greek and Russian Orthodox Churches).

-p Print the country codes and switching days from Julian to Gregorian
Calendar as they are assumed by ncal. The coun‐
try code as determined from the local environment is marked with an
asterisk.

-s country_code
Assume the switch from Julian to Gregorian Calendar at the date associated
with the country_code. If not specified,
ncal tries to guess the switch date from the local environment or falls back
to September 2, 1752. This was when
Great Britain and her colonies switched to the Gregorian Calendar.

-w Print the number of the week below each week column.

-y Display a calendar for the specified year. This option is implied when a
year but no month are specified on the com‐
mand line.

-3 Display the previous, current and next month surrounding today.

-1 Display only the current month. This is the default.

-A number
Months to add after. The specified number of months is added to the end of
the display. This is in addition to any
date range selected by the -y, -3, or -1 options. For example, “cal -y -B2 -
A2” shows everything from November of the
previous year to February of the following year. Negative numbers are
allowed, in which case the specified number of
months is subtracted. For example, “cal -y -B-6” shows July to December.
And “cal -A11” simply shows the next 12
months.

-B number
Months to add before. The specified number of months is added to the
beginning of the display. See -A for examples.

-C Completely switch to cal mode. For cal like output only, use -b instead.

-d yyyy-mm
Use yyyy-mm as the current date (for debugging of date selection).

-H yyyy-mm-dd
Use yyyy-mm-dd as the current date (for debugging of highlighting).

-M Weeks start on Monday.

-S Weeks start on Sunday.

-W number
First week of the year has at least number days.

-b Use oldstyle format for ncal output.

A single parameter specifies the year (1–9999) to be displayed; note the year
must be fully specified: “cal 89” will not dis‐
play a calendar for 1989. Two parameters denote the month and year; the month
is either a number between 1 and 12, or a full
or abbreviated name as specified by the current locale. Month and year default
to those of the current system clock and time
zone (so “cal -m 8” will display a calendar for the month of August in the current
year).
Not all options can be used together. For example the options -y, -3, and -1 are
mutually exclusive. If inconsistent options
are given, the later ones take precedence over the earlier ones.

A year starts on January 1.

Highlighting of dates is disabled if stdout is not a try.

NAME
touch - change file timestamps
SYNOPSIS
touch [OPTION]... FILE...

DESCRIPTION
Update the access and modification times of each FILE to the current time.

A FILE argument that does not exist is created empty, unless -c or -h is supplied.

A FILE argument string of - is handled specially and causes touch to change the
times of the file associated with standard
output.

Mandatory arguments to long options are mandatory for short options too.

-a change only the access time

-c, --no-create
do not create any files

-d, --date=STRING
parse STRING and use it instead of current time

-f (ignored)

-h, --no-dereference
affect each symbolic link instead of any referenced file (useful only on
systems that can change the timestamps of a
symlink)

-m change only the modification time


-r, --reference=FILE
use this file's times instead of current time

-t STAMP
use [[CC]YY]MMDDhhmm[.ss] instead of current time

--time=WORD
change the specified time: WORD is access, atime, or use: equivalent to -a
WORD is modify or mtime: equivalent to -m

--help display this help and exit

--version
output version information and exit
Note that the -d and -t options accept different time-date formats.

DATE STRING
The --date=STRING is a mostly free format human readable date string such as
"Sun, 29 Feb 2004 16:21:42 -0800" or "2004-02-29
16:21:42" or even "next Thursday". A date string may contain items indicating
calendar date, time of day, time zone, day of
week, relative time, relative date, and numbers. An empty string indicates the
beginning of the day. The date string format
is more complex than is easily documented here but is fully described in the info
documentation.

NAME
file — determine file type

SYNOPSIS
file [-bcdEhiklLNnprsSvzZ0] [--apple] [--exclude-quiet] [--extension] [--
mime-encoding] [--mime-type] [-e testname]
[-F separator] [-f namefile] [-m magicfiles] [-P name=value] file ...
file -C [-m magicfiles]
file [--help]

DESCRIPTION
This manual page documents version 5.45 of the file command.

file tests each argument in an attempt to classify it. There are three sets of tests,
performed in this order: filesystem
tests, magic tests, and language tests. The first test that succeeds causes the file
type to be printed.

The type printed will usually contain one of the words text (the file contains only
printing characters and a few common con‐
trol characters and is probably safe to read on an ASCII terminal), executable
(the file contains the result of compiling a
program in a form understandable to some UNIX kernel or another), or data
meaning anything else (data is usually “binary” or
non-printable). Exceptions are well-known file formats (core files, tar
archives) that are known to contain binary data.
When modifying magic files or the program itself, make sure to preserve these
keywords. Users depend on knowing that all the
readable files in a directory have the word “text” printed. Don't do as Berkeley
did and change “shell commands text” to
“shell script”.

The filesystem tests are based on examining the return from a stat(2) system call.
The program checks to see if the file is
empty, or if it's some sort of special file. Any known file types appropriate to the
system you are running on (sockets,
symbolic links, or named pipes (FIFOs) on those systems that implement them)
are intuited if they are defined in the system
header file <sys/stat.h>.

The magic tests are used to check for files with data in particular fixed formats.
The canonical example of this is a binary
executable (compiled program) a.out file, whose format is defined in <elf.h>,
<a.out.h> and possibly <exec.h> in the standard
include directory. These files have a “magic number” stored in a particular place
near the beginning of the file that tells the UNIX operating system that the file is a
binary executable, and which of several types thereof. The concept of a “magic
number” has been applied by extension to data files. Any file with some
invariant identifier at a small fixed offset into
the file can usually be described in this way. The information identifying these
files is read from /etc/magic and the com‐
piled magic file /usr/share/misc/magic.mgc, or the files in the directory
/usr/share/misc/magic if the compiled file does not
exist. In addition, if $HOME/.magic.mgc or $HOME/.magic exists, it will be
used in preference to the system magic files.

If a file does not match any of the entries in the magic file, it is examined to see
if it seems to be a text file. ASCII,
ISO-8859-x, non-ISO 8-bit extended-ASCII character sets (such as those used
on Macintosh and IBM PC systems), UTF-8-encoded
Unicode, UTF-16-encoded Unicode, and EBCDIC character sets can be
distinguished by the different ranges and sequences of
bytes that constitute printable text in each set. If a file passes any of these
tests, its character set is reported.
ASCII, ISO-8859-x, UTF-8, and extended-ASCII files are identified as “text”
because they will be mostly readable on nearly
any terminal; UTF-16 and EBCDIC are only “character data” because, while
they contain text, it is text that will require
translation before it can be read. In addition, file will attempt to determine other
characteristics of text-type files. If
the lines of a file are terminated by CR, CRLF, or NEL, instead of the Unix-
standard LF, this will be reported. Files that
contain embedded escape sequences or overstriking will also be identified.
Once file has determined the character set used in a text-type file, it will attempt
to determine in what language the file
is written. The language tests look for particular strings (cf. <names.h>) that can
appear anywhere in the first few blocks
of a file. For example, the keyword .br indicates that the file is most likely a
troff(1) input file, just as the keyword
struct indicates a C program. These tests are less reliable than the previous two
groups, so they are performed last. The
language test routines also test for some miscellany (such as tar(1) archives,
JSON files).

Any file that cannot be identified as having been written in any of the character
sets listed above is simply said to be
“data”.

OPTIONS

--apple
Causes the file command to output the file type and creator code as used by
older MacOS versions. The code consists
of eight letters, the first describing the file type, the latter the creator. This
option works properly only for
file formats that have the apple-style output defined.

-b, --brief
Do not prepend filenames to output lines (brief mode).

-C, --compile
Write a magic.mgc output file that contains a pre-parsed version of the
magic file or directory.

-c, --checking-printout
Cause a checking printout of the parsed form of the magic file. This is
usually used in conjunction with the -m op‐
tion to debug a new magic file before installing it.

-d Prints internal debugging information to stderr.

-E On filesystem errors (file not found etc), instead of handling the error as
regular output as POSIX mandates and keep
going, issue an error message and exit.

-e, --exclude testname


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 backwards compatibility.

cdf Prints details of Compound Document Files.

compress Checks for, and looks inside, compressed files.

csv Checks Comma Separated Value files.

elf Prints ELF file details, provided soft magic tests are enabled and the
elf magic is found.

json Examines JSON (RFC-7159) files by parsing them for compliance.

soft Consults magic files.

simh Examines SIMH tape files.

tar Examines tar files by verifying the checksum of the 512 byte tar
header. Excluding this test can provide
more detailed content description by using the soft magic method.

text A synonym for ‘ascii’.

--exclude-quiet
Like --exclude but ignore tests that file does not know about. This is
intended for compatibility with older ver‐
sions of file.

--extension
Print a slash-separated list of valid extensions for the file type found.

-F, --separator separator


Use the specified string as the separator between the filename and the file
result returned. Defaults to ‘:’.

-f, --files-from namefile


Read the names of the files to be examined from namefile (one per line) before the
argument list. Either namefile or
at least one filename argument must be present; to test the standard input,
use ‘-’ as a filename argument. Please
note that namefile is unwrapped and the enclosed filenames are processed
when this option is encountered and before
any further options processing is done. This allows one to process
multiple lists of files with different command
line arguments on the same file invocation. Thus if you want to set the
delimiter, you need to do it before you
specify the list of files, like: “-F @ -f namefile”, instead of: “-f namefile -F
@”.

-h, --no-dereference
This option causes symlinks not to be followed (on systems that support
symbolic links). This is the default if the
environment variable POSIXLY_CORRECT is not defined.

-i, --mime
Causes the file command to output mime type strings rather than the more
traditional human readable ones. Thus it
may say ‘text/plain; charset=us-ascii’ rather than “ASCII text”.

--mime-type, --mime-encoding
Like -i, but print only the specified element(s).

-k, --keep-going
Don't stop at the first match, keep going. Subsequent matches will be have
the string ‘\012- ’ prepended. (If you
want a newline, see the -r option.) The magic pattern with the highest
strength (see the -l option) comes first.

-l, --list
Shows a list of patterns and their strength sorted descending by magic(5)
strength which is used for the matching
(see also the -k option).

-L, --dereference
This option causes symlinks to be followed, as the like-named option in
ls(1) (on systems that support symbolic
links). This is the default if the environment variable
POSIXLY_CORRECT is defined.

-m, --magic-file magicfiles


Specify an alternate list of files and directories containing magic. This can
be a single item, or a colon-separated list. If a compiled magic file is found alongside
a file or directory, it will be used instead.

-N, --no-pad
Don't pad filenames so that they align in the output.

-n, --no-buffer
Force stdout to be flushed after checking each file. This is only useful if
checking a list of files. It is in‐
tended to be used by programs that want filetype output from a pipe.

-p, --preserve-date
On systems that support utime(3) or utimes(2), attempt to preserve the
access time of files analyzed, to pretend that
file never read them.

-P, --parameter name=value


Set various parameter limits.

Name Default Explanation


bytes 1M max number of bytes to read from file
elf_notes 256 max ELF notes processed
elf_phnum 2K max ELF program sections processed
elf_shnum 32K max ELF sections processed
elf_shsize 128MB max ELF section size processed
encoding 65K max number of bytes to determine encoding
indir 50 recursion limit for indirect magic
name 50 use count limit for name/use magic
regex 8K length limit for regex searches

-r, --raw
Don't translate unprintable characters to \ooo. Normally file translates
unprintable characters to their octal rep‐
resentation.

-s, --special-files Normally, file only attempts to read and determine the type of
argument files which stat(2) reports are ordinary
files. This prevents problems, because reading special files may have
peculiar consequences. Specifying the -s op‐
tion causes file to also read argument files which are block or character
special files. This is useful for deter‐
mining the filesystem types of the data in raw disk partitions, which are
block special files. This option also
causes file to disregard the file size as reported by stat(2) since on some
systems it reports a zero size for raw
disk partitions.

-S, --no-sandbox
On systems where libseccomp (https://github.com/seccomp/libseccomp) is
available, the -S option disables sandboxing
which is enabled by default. This option is needed for file to execute
external decompressing programs, i.e. when
the -z option is specified and the built-in decompressors are not
available. On systems where sandboxing is not
available, this option has no effect.

Note: This Debian version of file was built without seccomp support, so this
option has no effect.

-v, --version
Print the version of the program and exit.

-z, --uncompress
Try to look inside compressed files.

-Z, --uncompress-noreport
Try to look inside compressed files, but report information about the
contents only not the compression.

-0, --print0
Output a null character ‘\0’ after the end of the filename. Nice to cut(1) the
output. This does not affect the
separator, which is still printed.

If this option is repeated more than once, then file prints just the filename
followed by a NUL followed by the de‐
scription (or ERROR: text) followed by a second NUL for each entry.

--help Print a help message and exit.


ENVIRONMENT
The environment variable MAGIC can be used to set the default magic file name.
If that variable is set, then file will not
attempt to open $HOME/.magic. file adds “.mgc” to the value of this
variable as appropriate. The environment variable
POSIXLY_CORRECT controls (on systems that support symbolic links),
whether file will attempt to follow symlinks or not. If
set, then file follows symlink, otherwise it does not. This is also controlled by
the -L and -h options.
FILES
/usr/share/misc/magic.mgc Default compiled list of magic.
/usr/share/misc/magic Directory containing default magic files.

EXIT STATUS
file will exit with 0 if the operation was successful or >0 if an error was
encountered. The following errors cause diagnos‐
tic messages, but don't affect the program exit code (as POSIX requires), unless -
E is specified:
• A file cannot be found
• There is no permission to read a file
• The file type cannot be determined

You might also like