Sunteți pe pagina 1din 43

#1) cal: Displays the calendar.

 Syntax: cal [[month] year]


 Example: display the calendar for April 2018
 $ cal 4 2018
#2) date: Displays the system date and time.
 Syntax: date [+format]
 Example: Display the date in dd/mm/yy format
 $ date +%d/%m/%y
#3) banner: Prints a large banner on the standard output.
 Syntax: banner message
 Example: Print “Unix” as the banner
 $ banner Unix
#4) who: Displays the list of users currently logged in
 Syntax: who [option] … [file][arg1]
 Example: List all currently logged in users
 $ who
#5) whoami: Displays the user id of the currently logged in user.
 Syntax: whoami [option]
 Example: List currently logged in user
 $ whoami

CAT

escription
The cat command reads one or more files and prints their contents to
standard output. Files are read and output in the order they appear in the
command arguments.

Syntax
The syntax for the cat command is:

cat [options] [files]


Parameters or Arguments
options
Some of the options available for the cat command are:

Option Description

-b Starting at 1, number non-blank output lines.

Display control and non-printing characters followed by a $ symbol at the end


-e
of each line. (May require the -v option)

-n Starting at 1, number all output lines.

Each tab will display as ^I and each form feed will display as ^L. (May require
-t
the -v option)

-u Output is displayed unbuffered.

Display control and non-printing characters. Control characters print as ^B for


-v control-B. Non-ASCII characters with the high bit set display as "M-"
followed by their lower 7-bit value.

NOTE: While the options provided here work on most UNIX systems,
some UNIX flavors may have changed their meanings or uses. If you
experience an incompatibility with these options, please consult
the cat manual page (see man command) on your system for a list of
compatible options.
files
A list of file names separated by spaces that cat will concatenate the
contents of.

Operators
The following operators can be used with the cat command:
Operator Description

Redirect the output of the cat command to a file rather than standard output. The
>
destination file will be created if it doesn't exist and will be overwritten if it does.

Append the output of the cat command to the end of an existing file. The destination
>>
file will be created if it doesn't exist.

Send (or pipe) the output of the cat command into another command for further
|
processing.

Applies To
 Most UNIX variants including: FreeBSD, OpenBSD, Solaris, Illumos,
SmartOS

Type of Command
 System Executable

Example - Using cat to output the contents of a file to the


display
In this example the file named file1 contains the text: Learning cat with
TechOnTheNet is fun!
The following command uses the cat command to output the contents
of file1 to the display.

cat file1

In this screenshot, you can see that the contents of file1 are displayed as
expected.
Example - Using cat to output the contents of two files to the
display
Building on the previous example, we will use the cat command to output
the contents of two files to the display.
For this example the file named file1 contains the text: Learning cat with
TechOnTheNet is fun! and the file named file2contains the
text: Concatenating two files into one is even more fun.
The following command outputs the contents of the files file1 and file2 to
the display.

cat file1 file2

In this screenshot, you can see that the contents of file1 is displayed first
followed by the contents of file2.
Example - Using cat to redirect the contents of two files to
another file
In this example we will use the cat command to redirect the contents of two
files into another file.
The file named file1 contains the text: Learning cat with TechOnTheNet is
fun! and the file named file2 contains the text: Concatenating two files into
one is even more fun.
The following command redirects the contents of the files
named file1 and file2 to the file named all.

cat file1 file2 > all

To view the contents of the file named all we will also use the cat command
as we did in the first example.

cat all
As we can see in the following screenshot, the contents of the files
named file1 and file2 are sent into the file named all by the first command
and the contents of the file all is output to the display by the second
command.

Example - Using cat to append the contents of a file to the


end of another file
In this example we will append the contents of one file to the end of another
file.
For this example the file named file1 contains the text: Learning cat with
TechOnTheNet is fun! and the file named file2contains the
text: Concatenating two files into one is even more fun.
We will use the following cat command to append the contents of the
file file1 to the end of the file file2.

cat file1 >> file2

To view the contents of the file named file2 we will use the following cat
command:
cat file2

This screenshot shows the contents of file2 after the contents of file1 were
appended to the end of file2.

Example - Using cat to pipe the contents of a file into


another command
In this example we will use the cat command, the pipe operator and
the grep command to send the contents of a file to the standard input of
the grep command.
For this example the file named file1 contains the text: Learning cat with
TechOnTheNet is fun! and the file named file2contains the
text: Concatenating two files into one is even more fun.
The following cat command pipes or sends the contents of the
files file1 and file2 to the standard input of the grep command.

cat file1 file2 | grep "TechOnTheNet"


In this screenshot we can see that the contents of both file1 and file2 are
sent into the grep command. The grep command filters the output
displaying any lines that contain the string TechOnTheNet.

The line Learning cat with TechOnTheNet is fun! from the file

Description
The change directory (cd) command is built into the system shell and changes the
current working directory. The cd command can be used to either chan

Syntax
The syntax for the cd command is:

cd <directory>
chmod [option] mode files

Mode Description Mode Description

Who u=user, g=group, o=other, a=all (default) Who u=user, g=group, o=other, a=all (default)
+ means add permission + means add permission
- means remove permission - means remove permission
Opcode Opcode
= means assign permission and remove the = means assign permission and remove the
permission of unspecified fields permission of unspecified fields

r=Read, w=write, x=Execute, s=set uid bit, r=Read, w=write, x=Execute, s=set uid bit,
Permission t=sticky bit Permission t=sticky bit
u=user, g=group, o=other, l=mandatory locking u=user, g=group, o=other, l=mandatory locking

Example Example

Mode Description Mode Description

Who u=user, g=group, o=other, a=all (default) Who u=user, g=group, o=other, a=all (default)

+ means add permission + means add permission


- means remove permission - means remove permission
Opcode Opcode
= means assign permission and remove the = means assign permission and remove the
permission of unspecified fields permission of unspecified fields

r=Read, w=write, x=Execute, s=set uid bit, r=Read, w=write, x=Execute, s=set uid bit,
Permission t=sticky bit Permission t=sticky bit
u=user, g=group, o=other, l=mandatory locking u=user, g=group, o=other, l=mandatory locking

Example Example

Example

chmod 751 tech


chmod u=rwx, g=rx, o=x tech
chmod =r tech

Advertisement

chmod

The chmod command can be used in a couple of different ways, with permissions (or modes) set by numbers or by letters.
Permissions can be given to a user who owns the file (u = user), group of said user (g = group), everyone else (o = others) or all
users (a). And the basic permissions that can be given include read (r), write (w), and execute (x). There are also X, s, and t, but
they're less commonly used.

When using numbers you can use a numeric value such as 644 to set permissions. The position of the value represents to whom is
the permission given, and the actual value represents which (or how much) permissions are given as a sum total of each
permission's unique value.

First position (in the above example 6) refers to the user. Second refers to the group of the user, and the third refers to all others.

Numeric values for permissions are:

4 = read 2 = write 1 = execute

So a value of 4 will only give read rights, but a value of 6 will give read and write rights because it is a sum of 4 and 2. 5 will
give only read ane execute rights, and 7 will give all rights. Do this calculation for each numerical position and you'll end up with
the desired value. So in the example of 644 we're giving the user who owns the file the permission to read and write (but not
execute), the group of that user the permission to read only, and others the right to read only as well.
To set this mode with chmod on a file called important.txt we would simply run this command:

chmod 644 important.txt

Note that making a file executable, if it were a script or a program, amounts to simply giving someone or everyone a permission
to execute. If this was an important.sh bash script we could allow the owner to execute, and others to read with the 744 mode, or
everyone to execute with 755.

chmod 755 important.sh

Now, we can also use letters to accomplish the same thing, and we've already mentioned the relevant letters above. This is
probably easier to remember than using numbers. For example, to accomplish the 644 permissions above we would run this:

chmod u+rw,go+r important.txt

So we're saying file owner user gets read and write permissions, group and others get to read.

The second example, with the important.sh file being made executable we could just run this:

chmod u+rwx,go+rx important.sh

If important.sh already had permissions set to 644 we can add everyone execute rights by simply running:

chmod +x important.sh

Not

grep command in Unix/Linux


The grep filter searches a file for a particular pattern of characters, and displays all lines that contain that pattern.

yntax:
grep [options] pattern [files]
Options Description
-c : This prints only a count of the lines that match a pattern
-h : Display the matched lines, but do not display the filenames.
-i : Ignores, case for matching
-l : Displays list of a filenames only.
-n : Display the matched lines and their line numbers.
-v : This prints out all the lines that do not matches the pattern
-e exp : Specifies expression with this option. Can use multiple times.
-f file : Takes patterns from file, one per line.
-E : Treats pattern as an extended regular expression (ERE)
-w : Match whole word
-o : Print only the matched parts of a matching line,
with each such part on a separate output line.

Sample Commands
Consider the below file as an input.
$cat > geekfile.txt
unix is great os. unix is opensource. unix is free os.

learn operating system.

Unix linux which one you choose.

uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

1. Case insensitive search : The


-i option enables to search for a string case insensitively in the
give file. It matches the words like “UNIX”, “Unix”, “unix”.
$grep -i "UNix" geekfile.txt

Output:

unix is great os. unix is opensource. unix is free os.


Unix linux which one you choose.

uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

2. Displaying the count of number of matches : We can find the number of lines that matches the given
string/pattern
$grep -c "unix" geekfile.txt

Output:
2

3. Display the file names that matches the pattern : We can just display the files that contains the given
string/pattern.
$grep -l "unix" *

or

$grep -l "unix" f1.txt f2.txt f3.xt f4.txt

Output:
geekfile.txt

4. Checking for the whole words in a file : By


default, grep matches the given string/pattern even if it
found as a substring in a file. The -w option to grep makes it match only the whole
words.
$ grep -w "unix" geekfile.txt

Output:
unix is great os. unix is opensource. unix is free os.

uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

5. Displaying only the matched pattern : By


default, grep displays the entire line which has the
matched string. We can make the grep to display only the matched string by using the -
o option.
$ grep -o "unix" geekfile.txt

Output:
unix

unix

unix

unix

unix

unix

6. Show line number while displaying the output using grep -n : To show the line number of file with the line
matched.
$ grep -n "unix" geekfile.txt

Output:
1:unix is great os. unix is opensource. unix is free os.

4:uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

7. Inverting the pattern match : You


can display the lines that are not matched with the specified
search sting pattern using the -v option.
$ grep -v "unix" geekfile.txt

Output:
learn operating system.
Unix linux which one you choose.

8. Matching the lines that start with a string : The


^ regular expression pattern specifies the start of a
line. This can be used in grep to match the lines which start with the given string or
pattern.
$ grep "^unix" geekfile.txt

Output:
unix is great os. unix is opensource. unix is free os.

9. Matching the lines that end with a string : The


$ regular expression pattern specifies the end of a
line. This can be used in grep to match the lines which end with the given string or
pattern.
$ grep "os$" geekfile.txt

10.Specifies expression with -e option. Can use multiple times :


$grep –e "Agarwal" –e "Aggarwal" –e "Agrawal" geekfile.txt

11. -f file option Takes patterns from file, one per line.
$cat pattern.txt

Agarwal
Aggarwal
Agrawal
$grep –f pattern.txt geekfile.txt

This article is contributed by Akshay Rajput. If you like GeeksforGeeks and would like to
contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to
contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main
page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Article Tags :
Articles

Linux-Unix

linux-command

Basic Interviews questions and Answer for QA and

Test Engineer
I am writing this blog for people who want to explore software testing as

there carrier.Here are some interview questions for your reference

 Classic

 Flipcard

 Magazine

 Mosaic

 Sidebar

 Snapshot

 Timeslide

SQL Statements and there Syntax

What are SQL Joins and Type of Joins?

How to Handle Popup Window in Selenium using Java

Complex SQL Queries for finding highest salary

How to count no. of links on webpage and print using selenium2 using java

SQL for QA and Testing Engineer

Configuring SDK ADT Bundle for mobile Automation

Unix List of Basic Commands for QA and Test Engineer


Unix List of Basic Commands for QA and Test Engineer
Unix List of Basic Commands for QA and Test Engineer

File and directory listing Commands

$ ls command is used for directory and file listing with there permission.

$ ls -l list files in current directory.

$ ls -a list hidden files.

Directories commands

$ pwd -command is used for knowing user current working directory or you can say print working directory.
$ cd - similar to DOS cd .it is use to change directory.

$ mkdir - use to create new directory.

$ rmdir - use to remove directory.

File Manipulation commands

$ cat filename - command is use to display file contents without paging.

$ cp source destination - command is use to copy file.

$ mv oldname newname - command is use to rename file .

$ rm filename - command use to delete file.

$ pico filename - command use to create or modify file.

$ More filename -List the contents of file pausing after each screen (press Space to continue listing).

$ grep string file-Search file for occurrences of string.

$ less filename - Display filename one screenful.A pager similar to (better than) more.

$ pg filename - View filename one screenfull at atime (a pager).

Special Control Characters

The control characters that have special meanings in a UNIX environment. Denoted by the character ^ followed by a letter, each control
character can be generated by holding down Control and pressing the specified letter, then releasing both keys.

^c

Interrupt a process (applicable for most processes); used to halt a process immediately.
Pressing ^c, for example, enables you to stop the listing of a long file. However, if the file is very long, there may be a noticeable time delay before the
process is actually interrupted.

^d

Terminate a process; end-of-file marker (EOF). If a process does not have a clean termination command and pressing ^c does not work, try pressing
^d.

^s

Suspend terminal output to your system. To resume terminal output, press ^q. ^s is usually referred to as XON.
To view text a page at a time, use the more command.

^q

Resume terminal output suspended by pressing ^s (see above). ^q is usually referred to as XOFF.

^z

Suspend the foreground process, that is, place the current active program in a paused state.
Type the fg command to reactivate a process in the foreground. A foreground process will usually keep control of your keyboard and terminal.
Type the bg command to reactivate a process in the background. A background process will let you type other commands on the keyboard while it is
running in a detached state.

^u

Erase command line.


^w

Erase previous word on a UNIX command line. A word is a string of characters separated by a space or tab.

^r Retype current command line

OTHER COMMANDS
$ print file -Send file to the UNIX laser printer.
$ man command - Display information about command.
$ apropos keyword - List commands/programs that contain keyword in their description.
$ du - List the number of Kbytes for each directory below current working directory.
$ talk username - Interactively communicate with username; username has to be logged-in.
$ finger username - Find the username for username.
$ w - Display current activity on the system.
$ who - Show users that are currently logged-in.
$ tin - A program to read a collection of newsgroups (new articles arrive daily).
$ help [command] - If specified without command, a brief introduction is listed.If command is specified, help displays the man page for command.
$ pine - Send email through the Internet
$ quota –v - Display disk usage and disk quota. This command does not display your email quota.
$ mydiskspace - Display uhunix disk usage only. This command does not display your email quota.
$ write username - Writes files or text to username.
$ !! - Repeats last command.

Process management
$ kill - Command use to terminate process.example: kill - 5555
$ nice program name - Command use to run program with lower priority.Recommended for running background processes.

$ ps - Command use to list no of processes running in a system.


$ top - show (continuously) what process(es) is running.

SQL Statement Syntax


AND / OR SELECT column_name(s) FROM table_name WHERE condition
AND|OR condition;
ALTER TABLE ALTER TABLE table_name ADD column_name datatype ;

or

ALTER TABLE table_name DROP COLUMN column_name;

AS (alias) SELECT column_name AS column_alias FROM table_name;

or

SELECT column_name FROM table_name AS table_alias;

BETWEEN SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND
value2;

CREATE DATABASE CREATE DATABASE database_name;

CREATE TABLE CREATE TABLE table_name (column_name1 data_type,


column_name2 data_type,column_name2 data_type,...);

CREATE INDEX CREATE INDEX index_name ON table_name (column_name);

or
CREATE UNIQUE INDEX index_name ON table_name (column_name);

CREATE VIEW CREATE VIEW view_name AS SELECT column_name(s)


FROM table_name WHERE condition;

DELETE DELETE FROM table_name WHERE some_column=some_value;

or

DELETE FROM table_name ;

DELETE * FROM table_name ;

DROP DATABASE DROP DATABASE database_name;

DROP INDEX DROP INDEX table_name.index_name (SQL Server)


DROP INDEX index_name ON table_name (MS Access)
DROP INDEX index_name (DB2/Oracle);
ALTER TABLE table_name DROP INDEX index_name (MySQL)

DROP TABLE DROP TABLE table_name;


GROUP BY SELECT column_name, aggregate_function(column_name);
FROM table_name WHERE column_name operator value
GROUP BY column_name;

HAVING SELECT column_name, aggregate_function(column_name)


FROM table_name WHERE column_name operator value
GROUP BY column_name HAVING aggregate_function(column_name) operator value;

IN SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,..);

INSERT INTO INSERT INTO table_name VALUES (value1, value2, value3,....);

or

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,....);

INNER JOIN SELECT column_name(s) FROM table_name1


INNER JOIN table_name2 ON table_name1.column_name=table_name2.column_name;

LEFT JOIN SELECT column_name(s) FROM table_name1 LEFT JOIN table_name2 ON


table_name1.column_name=table_name2.column_name;

RIGHT JOIN SELECT column_name(s) FROM table_name1 RIGHT JOIN table_name2 ON


table_name1.column_name=table_name2.column_name;

FULL JOIN SELECT column_name(s) FROM table_name1


FULL JOIN table_name2 ON table_name1.column_name=table_name2.column_name;

LIKE SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern;

ORDER BY SELECT column_name(s) FROM table_name


ORDER BY column_name [ASC|DESC];

SELECT SELECT column_name(s) FROM table_name;

SELECT * SELECT *FROM table_name;

SELECT DISTINCT SELECT DISTINCT column_name(s)FROM table_name;

SELECT INTO SELECT * INTO new_table_name [IN externaldatabase]


FROM old_table_name;

or

SELECT column_name(s) INTO new_table_name [IN externaldatabase] FROM old_table_name;

SELECT TOP SELECT TOP number|percent column_name(s)


FROM table_name;
TRUNCATE TABLE TRUNCATE TABLE table_name
UNION SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2;

UNION ALL SELECT column_name(s) FROM table_name1


UNION ALL
SELECT column_name(s) FROM table_name2;

UPDATE UPDATE table_name SET column1=value, column2=value,...


WHERE some_column=some_value ;

WHERE SELECT column_name(s) FROM table_name


WHERE column_name operator value;
; Complex SQL Queries for finding highest salary
Q1 Find the second Highest salary?

This below query can be used in any DB.


select max(salary) from emp where salary not in (select max(salary) from emp);

MySQL

select * from (select distinct salary from emp order by salary desc limit 2) as
emp order by salary asc limit 1;

select min(salary) from emp where salary in (select distinct salary from emp order by salary desc limit 2)
;

select salary from emp order by salary desc limit 1,1;

Note :LIMIT is Phrases as LIMIT X,Y

X is the starting point (remember the first record is 0) and Y is the duration (how many records to
display).

so it will also return the second highest salary.

MSSql Server

select top 1 salary from (select distinct top 2 salary from emp order by salary desc) as
emp order by salary asc ;

select min(salary) from emp where salary in (select distinct top 2 salary from emp order by salary desc);

Q2 Find the nth Highest salary?


MySQL
by using below query you can retrieve n highest salary by replace 'n' with required number.

select salary from emp order by salary desc limit n,1;

Through sub-query also you can retrieve n highest salary by replace 'n' with required number.

select * from (select distinct salary from emp order by salary desc limit n) as
emp order by salary asc limit 1;

MSSql Server

Replace n in the below queries and retrieve any highest salary.

select top 1 salary from (select distinct top n salary from emp order by salary desc) as
emp order by salary asc ;

select min(salary) from emp where salary in (select distinct top n salary from emp order by salary desc);

please comment if there is any possibility of corrections thanks

Posted 25th September 2013 by ashok malla


Location: Asia

Labels: Highest Limit MS sql server Mysql salary Top

Basic UNIX commands


Note: not all of these are actually part of UNIX itself, and you may not find them on
all UNIX machines. But they can all be used on turing in essentially the same way, by
typing the command and hitting return. Note that some of these commands are
different on non-Solaris machines - see SunOS differences.
If you've made a typo, the easiest thing to do is hit CTRL-u to cancel the whole line.
But you can also edit the command line (see the guide to More UNIX).
UNIX is case-sensitive.

Files
 ls --- lists your files
ls -l --- lists your files in 'long format', which contains lots of useful
information, e.g. the exact size of the file, who owns the file and who has the
right to look at it, and when it was last modified.
ls -a --- lists all files, including the ones whose filenames begin in a dot, which
you do not always want to see.
There are many more options, for example to list files by size, by date,
recursively etc.
 more filename --- shows the first part of a file, just as much as will fit on one
screen. Just hit the space bar to see more or q to quit. You can use /pattern to
search for a pattern.
 emacs filename --- is an editor that lets you create and edit a file. See
the emacs page.
 mv filename1 filename2 --- moves a file (i.e. gives it a different name, or
moves it into a different directory (see below)
 cp filename1 filename2 --- copies a file
 rm filename --- removes a file. It is wise to use the option rm -i, which will ask
you for confirmation before actually deleting anything. You can make this your
default by making an alias in your .cshrc file.
 diff filename1 filename2 --- compares files, and shows where they differ
 wc filename --- tells you how many lines, words, and characters there are in a
file
 chmod options filename --- lets you change the read, write, and execute
permissions on your files. The default is that only you can look at them and
change them, but you may sometimes want to change these permissions. For
example, chmod o+r filename will make the file readable for everyone,
and chmod o-r filename will make it unreadable for others again. Note that
for someone to be able to actually look at the file the directories it is in need
to be at least executable. See help protection for more details.
 File Compression
o gzip filename --- compresses files, so that they take up much less space.
Usually text files compress to about half their original size, but it
depends very much on the size of the file and the nature of the
contents. There are other tools for this purpose, too (e.g. compress),
but gzip usually gives the highest compression rate. Gzip produces files
with the ending '.gz' appended to the original filename.
o gunzip filename --- uncompresses files compressed by gzip.
o gzcat filename --- lets you look at a gzipped file without actually having
to gunzip it (same as gunzip -c). You can even print it directly,
using gzcat filename | lpr
 printing
o lpr filename --- print. Use the -P option to specify the printer name if
you want to use a printer other than your default printer. For example,
if you want to print double-sided, use 'lpr -Pvalkyr-d', or if you're at
CSLI, you may want to use 'lpr -Pcord115-d'. See 'help printers' for more
information about printers and their locations.
o lpq --- check out the printer queue, e.g. to get the number needed for
removal, or to see how many other files will be printed before yours will
come out
o lprm jobnumber --- remove something from the printer queue. You can
find the job number by using lpq. Theoretically you also have to specify
a printer name, but this isn't necessary as long as you use your default
printer in the department.
o genscript --- converts plain text files into postscript for printing, and
gives you some options for formatting. Consider making an alias
like alias ecop 'genscript -2 -r \!* | lpr -h -Pvalkyr' to print two pages on
one piece of paper.
o dvips filename --- print .dvi files (i.e. files produced by LaTeX). You can
use dviselect to print only selected pages. See the LaTeX page for more
information about how to save paper when printing drafts.

Directories
Directories, like folders on a Macintosh, are used to group files together in a
hierarchical structure.

 mkdir dirname --- make a new directory


 cd dirname --- change directory. You basically 'go' to another directory, and
you will see the files in that directory when you do 'ls'. You always start out in
your 'home directory', and you can get back there by typing 'cd' without
arguments. 'cd ..' will get you one level up from your current position. You
don't have to walk along step by step - you can make big leaps or avoid
walking around by specifying pathnames.
 pwd --- tells you where you currently are.

Finding things
 ff --- find files anywhere on the system. This can be extremely useful if you've
forgotten in which directory you put a file, but do remember the name. In
fact, if you use ff -p you don't even need the full name, just the beginning. This
can also be useful for finding other things on the system, e.g. documentation.
 grep string filename(s) --- looks for the string in the files. This can be useful a
lot of purposes, e.g. finding the right file among many, figuring out which is
the right version of something, and even doing serious corpus work. grep
comes in several varieties (grep, egrep, and fgrep) and has a lot of very
flexible options. Check out the man pages if this sounds good to you.

About other people


 w --- tells you who's logged in, and what they're doing. Especially useful: the
'idle' part. This allows you to see whether they're actually sitting there typing
away at their keyboards right at the moment.
 who --- tells you who's logged on, and where they're coming from. Useful if
you're looking for someone who's actually physically in the same building as
you, or in some other particular location.
 finger username --- gives you lots of information about that user, e.g. when
they last read their mail and whether they're logged in. Often people put
other practical information, such as phone numbers and addresses, in a file
called .plan. This information is also displayed by 'finger'.
 last -1 username --- tells you when the user last logged on and off and from
where. Without any options, last will give you a list of everyone's logins.
 talk username --- lets you have a (typed) conversation with another user
 write username --- lets you exchange one-line messages with another user
 elm --- lets you send e-mail messages to people around the world (and, of
course, read them). It's not the only mailer you can use, but the one we
recommend. See the elm page, and find out about the departmental mailing
lists (which you can also find in /user/linguistics/helpfile).

About your (electronic) self


 whoami --- returns your username. Sounds useless, but isn't. You may need to
find out who it is who forgot to log out somewhere, and make sure *you*
have logged out.
 finger & .plan files
of course you can finger yourself, too. That can be useful e.g. as a quick check
whether you got new mail. Try to create a useful .plan file soon. Look at other
people's .plan files for ideas. The file needs to be readable for everyone in
order to be visible through 'finger'. Do 'chmod a+r .plan' if necessary. You
should realize that this information is accessible from anywhere in the world,
not just to other people on turing.
 passwd --- lets you change your password, which you should do regularly (at
least once a year). See the LRB guide and/or look at help password.
 ps -u yourusername --- lists your processes. Contains lots of information about
them, including the process ID, which you need if you have to kill a process.
Normally, when you have been kicked out of a dialin session or have
otherwise managed to get yourself disconnected abruptly, this list will contain
the processes you need to kill. Those may include the shell (tcsh or whatever
you're using), and anything you were running, for example emacs or elm. Be
careful not to kill your current shell - the one with the number closer to the
one of the ps command you're currently running. But if it happens, don't
panic. Just try again :) If you're using an X-display you may have to kill some X
processes before you can start them again. These will show only when you
use ps -efl, because they're root processes.
 kill PID --- kills (ends) the processes with the ID you gave. This works only for
your own processes, of course. Get the ID by using ps. If the process doesn't
'die' properly, use the option -9. But attempt without that option first,
because it doesn't give the process a chance to finish possibly important
business before dying. You may need to kill processes for example if your
modem connection was interrupted and you didn't get logged out properly,
which sometimes happens.
 quota -v --- show what your disk quota is (i.e. how much space you have to
store files), how much you're actually using, and in case you've exceeded your
quota (which you'll be given an automatic warning about by the system) how
much time you have left to sort them out (by deleting or gzipping some, or
moving them to your own computer).
 du filename --- shows the disk usage of the files and directories
in filename (without argument the current directory is used). du -s gives only a
total.
 last yourusername --- lists your last logins. Can be a useful memory aid for
when you were where, how long you've been working for, and keeping track
of your phonebill if you're making a non-local phonecall for dialling in.

Connecting to the outside world


 nn --- allows you to read news. It will first let you read the news local to turing,
and then the remote news. If you want to read only the local or remote news,
you can use nnl or nnr, respectively. To learn more about nn type nn, then
\tty{:man}, then \tty{=.*}, then \tty{Z}, then hit the space bar to step through
the manual. Or look at the man page. Or check out the hypertext nn FAQ -
probably the easiest and most fun way to go.
 rlogin hostname --- lets you connect to a remote host
 telnet hostname --- also lets you connect to a remote host.
Use rlogin whenever possible.
 ftp hostname --- lets you download files from a remote host which is set up as
an ftp-server. This is a common method for exchanging academic papers and
drafts. If you need to make a paper of yours available in this way, you can
(temporarily) put a copy in /user/ftp/pub/TMP. For more permanent
solutions, ask Emma. The most important commands within ftp are get for
getting files from the remote machine, and put for putting them there
(mget and mput let you specify more than one file at once). Sounds
straightforward, but be sure not to confuse the two, especially when your
physical location doesn't correspond to the direction of the ftp connection
you're making. ftp just overwrites files with the same filename. If you're
transferring anything other than ASCII text, use binary mode.
 lynx --- lets you browse the web from an ordinary terminal. Of course you can
see only the text, not the pictures. You can type any URL as an argument to
the G command. When you're doing this from any Stanford host you can leave
out the .stanford.edu part of the URL when connecting to Stanford URLs.
Type H at any time to learn more about lynx, and Q to exit.

Miscellaneous tools
 webster word --- looks up the word in an electronic version of Webster's
dictionary and returns the definition(s)
 date --- shows the current date and time.
 cal --- shows a calendar of the current month. Use e.g., 'cal 10 1995' to get
that for October 95, or 'cal 1995' to get the whole year.

You can find out more about these commands by looking up their manpages:
man commandname --- shows you the manual page for the command

For further ways of obtaining help, look at the pages with electronic sources of
information and non-electronic sources.
More UNIX commands

Back up to the Main Computing Page

15 Basic ‘ls’ Command Examples in Linux


by Ravi Saive | Published: August 22, 2012 | Last Updated: March 21, 2018
Download Your Free eBooks NOW - 10 Free Linux eBooks for Administrators | 4 Free Shell Scripting
eBooks

ls command is one of the most frequently used command in Linux. I believe ls command is the first command you may use when

you get into the command prompt of Linux Box.

We use ls command daily basis and frequently even though we may not aware and never use all the ls option available. In this

article, we’ll be discussing basic ls command where we have tried to cover as much parameters as possible.

Linux ls Command

1. List Files using ls with no option

ls with no option list files and directories in bare format where we won’t be able to view details like file types, size, modified date

and time, permission and links etc.


# ls
0001.pcap Desktop Downloads index.html install.log.syslog Pictures Templates
anaconda-ks.cfg Documents fbcmd_update.php install.log Music Public Videos

2 List Files With option –l

Here, ls -l (-l is character not one) shows file or directory, size, modified date and time, file or folder name and owner of file and

its permission.
# ls -l
total 176
-rw-r--r--. 1 root root 683 Aug 19 09:59 0001.pcap
-rw-------. 1 root root 1586 Jul 31 02:17 anaconda-ks.cfg
drwxr-xr-x. 2 root root 4096 Jul 31 02:48 Desktop
drwxr-xr-x. 2 root root 4096 Jul 31 02:48 Documents
drwxr-xr-x. 4 root root 4096 Aug 16 02:55 Downloads
-rw-r--r--. 1 root root 21262 Aug 12 12:42 fbcmd_update.php
-rw-r--r--. 1 root root 46701 Jul 31 09:58 index.html
-rw-r--r--. 1 root root 48867 Jul 31 02:17 install.log
-rw-r--r--. 1 root root 11439 Jul 31 02:13 install.log.syslog
drwxr-xr-x. 2 root root 4096 Jul 31 02:48 Music
drwxr-xr-x. 2 root root 4096 Jul 31 02:48 Pictures
drwxr-xr-x. 2 root root 4096 Jul 31 02:48 Public
drwxr-xr-x. 2 root root 4096 Jul 31 02:48 Templates
drwxr-xr-x. 2 root root 4096 Jul 31 02:48 Videos

3. View Hidden Files

List all files including hidden file starting with ‘.‘.


# ls -a
. .bashrc Documents .gconfd install.log .nautilus .pulse-cookie
.. .cache Downloads .gnome2 install.log.syslog .netstat.swp .recently-used.xbel
0001.pcap .config .elinks .gnome2_private .kde .opera .spice-vdagent
anaconda-ks.cfg .cshrc .esd_auth .gtk-bookmarks .libreoffice Pictures .tcshrc
.bash_history .dbus .fbcmd .gvfs .local .pki Templates
.bash_logout Desktop fbcmd_update.php .ICEauthority .mozilla Public Videos
.bash_profile .digrc .gconf index.html Music .pulse .wireshark

4. List Files with Human Readable Format with option -lh

With combination of -lh option, shows sizes in human readable format.


# ls -lh
total 176K
-rw-r--r--. 1 root root 683 Aug 19 09:59 0001.pcap
-rw-------. 1 root root 1.6K Jul 31 02:17 anaconda-ks.cfg
drwxr-xr-x. 2 root root 4.0K Jul 31 02:48 Desktop
drwxr-xr-x. 2 root root 4.0K Jul 31 02:48 Documents
drwxr-xr-x. 4 root root 4.0K Aug 16 02:55 Downloads
-rw-r--r--. 1 root root 21K Aug 12 12:42 fbcmd_update.php
-rw-r--r--. 1 root root 46K Jul 31 09:58 index.html
-rw-r--r--. 1 root root 48K Jul 31 02:17 install.log
-rw-r--r--. 1 root root 12K Jul 31 02:13 install.log.syslog
drwxr-xr-x. 2 root root 4.0K Jul 31 02:48 Music
drwxr-xr-x. 2 root root 4.0K Jul 31 02:48 Pictures
drwxr-xr-x. 2 root root 4.0K Jul 31 02:48 Public
drwxr-xr-x. 2 root root 4.0K Jul 31 02:48 Templates
drwxr-xr-x. 2 root root 4.0K Jul 31 02:48 Videos

5. List Files and Directories with ‘/’ Character at the end

Using -F option with ls command, will add the ‘/’ Character at the end each directory.
# ls -F
0001.pcap Desktop/ Downloads/ index.html install.log.syslog Pictures/ Templates/
anaconda-ks.cfg Documents/ fbcmd_update.php install.log Music/ Public/ Videos/

6. List Files in Reverse Order

The following command with ls -r option display files and directories in reverse order.
# ls -r
Videos Public Music install.log fbcmd_update.php Documents anaconda-ks.cfg
Templates Pictures install.log.syslog index.html Downloads Desktop 0001.pcap
7. Recursively list Sub-Directories

ls -R option will list very long listing directory trees. See an example of output of the command.
# ls -R
total 1384
-rw-------. 1 root root 33408 Aug 8 17:25 anaconda.log
-rw-------. 1 root root 30508 Aug 8 17:25 anaconda.program.log
./httpd:
total 132
-rw-r--r-- 1 root root 0 Aug 19 03:14 access_log
-rw-r--r--. 1 root root 61916 Aug 10 17:55 access_log-20120812
./lighttpd:
total 68
-rw-r--r-- 1 lighttpd lighttpd 7858 Aug 21 15:26 access.log
-rw-r--r--. 1 lighttpd lighttpd 37531 Aug 17 18:21 access.log-20120819
./nginx:
total 12
-rw-r--r--. 1 root root 0 Aug 12 03:17 access.log
-rw-r--r--. 1 root root 390 Aug 12 03:17 access.log-20120812.gz

8. Reverse Output Order

With combination of -ltr will shows latest modification file or directory date as last.
# ls -ltr
total 176
-rw-r--r--. 1 root root 11439 Jul 31 02:13 install.log.syslog
-rw-r--r--. 1 root root 48867 Jul 31 02:17 install.log
-rw-------. 1 root root 1586 Jul 31 02:17 anaconda-ks.cfg
drwxr-xr-x. 2 root root 4096 Jul 31 02:48 Desktop
drwxr-xr-x. 2 root root 4096 Jul 31 02:48 Videos
drwxr-xr-x. 2 root root 4096 Jul 31 02:48 Templates
drwxr-xr-x. 2 root root 4096 Jul 31 02:48 Public
drwxr-xr-x. 2 root root 4096 Jul 31 02:48 Pictures
drwxr-xr-x. 2 root root 4096 Jul 31 02:48 Music
drwxr-xr-x. 2 root root 4096 Jul 31 02:48 Documents
-rw-r--r--. 1 root root 46701 Jul 31 09:58 index.html
-rw-r--r--. 1 root root 21262 Aug 12 12:42 fbcmd_update.php
drwxr-xr-x. 4 root root 4096 Aug 16 02:55 Downloads
-rw-r--r--. 1 root root 683 Aug 19 09:59 0001.pcap

9. Sort Files by File Size

With combination of -lS displays file size in order, will display big in size first.
# ls -lS
total 176
-rw-r--r--. 1 root root 48867 Jul 31 02:17 install.log
-rw-r--r--. 1 root root 46701 Jul 31 09:58 index.html
-rw-r--r--. 1 root root 21262 Aug 12 12:42 fbcmd_update.php
-rw-r--r--. 1 root root 11439 Jul 31 02:13 install.log.syslog
drwxr-xr-x. 2 root root 4096 Jul 31 02:48 Desktop
drwxr-xr-x. 2 root root 4096 Jul 31 02:48 Documents
drwxr-xr-x. 4 root root 4096 Aug 16 02:55 Downloads
drwxr-xr-x. 2 root root 4096 Jul 31 02:48 Music
drwxr-xr-x. 2 root root 4096 Jul 31 02:48 Pictures
drwxr-xr-x. 2 root root 4096 Jul 31 02:48 Public
drwxr-xr-x. 2 root root 4096 Jul 31 02:48 Templates
drwxr-xr-x. 2 root root 4096 Jul 31 02:48 Videos
-rw-------. 1 root root 1586 Jul 31 02:17 anaconda-ks.cfg
-rw-r--r--. 1 root root 683 Aug 19 09:59 0001.pcap
10. Display Inode number of File or Directory

We can see some number printed before file / directory name. With -i options list file / directory with inode number.
# ls -i
20112 0001.pcap 23610 Documents 23793 index.html 23611 Music 23597 Templates
23564 anaconda-ks.cfg 23595 Downloads 22 install.log 23612 Pictures 23613 Videos
23594 Desktop 23585 fbcmd_update.php 35 install.log.syslog 23601 Public

11. Shows version of ls command

Check version of ls command.

# ls --version
ls (GNU coreutils) 8.4
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by Richard M. Stallman and David MacKenzie.

12. Show Help Page

List help page of ls command with their option.

# ls --help
Usage: ls [OPTION]... [FILE]...

13. List Directory Information

With ls -l command list files under directory /tmp. Wherein with -ld parameters displays information of /tmpdirectory.
# ls -l /tmp
total 408
drwx------. 2 narad narad 4096 Aug 2 02:00 CRX_75DAF8CB7768
-r--------. 1 root root 384683 Aug 4 12:28 htop-1.0.1.tar.gz
drwx------. 2 root root 4096 Aug 4 11:20 keyring-6Mfjnk
drwx------. 2 root root 4096 Aug 16 01:33 keyring-pioZJr
drwx------. 2 gdm gdm 4096 Aug 21 11:26 orbit-gdm
drwx------. 2 root root 4096 Aug 19 08:41 pulse-gl6o4ZdxQVrX
drwx------. 2 narad narad 4096 Aug 4 08:16 pulse-UDH76ExwUVoU
drwx------. 2 gdm gdm 4096 Aug 21 11:26 pulse-wJtcweUCtvhn
-rw-------. 1 root root 300 Aug 16 03:34 yum_save_tx-2012-08-16-03-34LJTAa1.yumtx
# ls -ld /tmp/
drwxrwxrwt. 13 root root 4096 Aug 21 12:48 /tmp/

14. Display UID and GID of Files

To display UID and GID of files and directories. use option -n with ls command.
# ls -n
total 36
drwxr-xr-x. 2 500 500 4096 Aug 2 01:52 Downloads
drwxr-xr-x. 2 500 500 4096 Aug 2 01:52 Music
drwxr-xr-x. 2 500 500 4096 Aug 2 01:52 Pictures
-rw-rw-r--. 1 500 500 12 Aug 21 13:06 tmp.txt
drwxr-xr-x. 2 500 500 4096 Aug 2 01:52 Videos
15. ls command and its Aliases

We have made alias for ls command, when we execute ls command it’ll take -l option by default and display long listing as

mentioned earlier.
# alias ls="ls -l"

Note: We can see number of alias available in your system with below alias command and same can be unalias as shown below

example.
# alias
alias cp='cp -i'
alias l.='ls -d .* --color=auto'
alias ll='ls -l --color=auto'
alias ls='ls --color=auto'
alias mv='mv -i'
alias rm='rm -i'
alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'

To remove an alias previously defined, just use the unalias command.

# unalias ls

In our next article we’ll cover up more or advanced ls command with their examples. Also I suggest you to go through

some interview questions on ls command and also if we’ve missed anything in the list, please update us via comment section.

SHARE

wc -l : Prints the number of lines in a file.


wc -w : prints the number of words in a file.
wc -c : Displays the count of bytes in a file.
wc -m : prints the count of characters from a file.
wc -L : prints only the length of the longest line in a file
0

So, let’s see how we can use the ‘wc‘ command with their few available arguments and examples in this article. We have used

the ‘tecmint.txt‘ file for testing the commands. Let’s find out the output of the file using cat command as shown below.

[root@tecmint ~]# cat tecmint.txt

Red Hat

CentOS

Fedora

Debian

Scientific Linux

OpenSuse

Ubuntu

Xubuntu

Linux Mint

Pearl Linux

Slackware

Mandriva

1. A Basic Example of WC Command


The ‘wc‘ command without passing any parameter will display a basic result of ”tecmint.txt‘ file. The three numbers shown

below are 12 (number of lines), 16 (number of words) and 112 (number of bytes) of the file.

[root@tecmint ~]# wc tecmint.txt

12 16 112 tecmint.txt

2. Count Number of Lines


To count number of newlines in a file use the option ‘-l‘, which prints the number of lines from a given file. Say, the following

command will display the count of newlines in a file. In the output the first filed assigned as count and second field is the name of

file.

[root@tecmint ~]# wc -l tecmint.txt

12 tecmint.txt

3. Display Number of Words


Using ‘-w‘ argument with ‘wc‘ command prints the number of words in a file. Type the following command to count the words

in a file.

[root@tecmint ~]# wc -w tecmint.txt

16 tecmint.txt

4. Count Number of Bytes and Characters


When using options ‘-c‘ and ‘-m‘ with ‘wc‘ command will print the total number of bytes and charactersrespectively in a file.

[root@tecmint ~]# wc -c tecmint.txt

112 tecmint.txt

[root@tecmint ~]# wc -m tecmint.txt

112 tecmint.txt

5. Display Length of Longest Line


The ‘wc‘ command allow an argument ‘-L‘, it can be used to print out the length of longest (number of characters) line in a file.

So, we have the longest character line (‘Scientific Linux‘) in a file.

[root@tecmint ~]# wc -L tecmint.txt

16 tecmint.txt

6. Check More WC Options


For more information and help on the wc command, simple run the ‘wc –help‘ or ‘man wc‘ from the command line.

[root@tecmint ~]# wc --help

Usage: wc [OPTION]... [FILE]...


or: wc [OPTION]... --files0-from=F

Print newline, word, and byte counts for each FILE, and a total line if

more than one FILE is specified. With no FILE, or when FILE is -,

read standard input.

-c, --bytes print the byte counts

-m, --chars print the character counts

-l, --lines print the newline counts

-L, --max-line-length print the length of the longest line

-w, --words print the word counts

--help display this help and exit

--version output version information and exit

Report wc bugs to bug-coreutils@gnu.org

GNU coreutils home page: <http://www.gnu.org/software/coreutils/>

General help using GNU software: <http://www.gnu.org/gethelp/>

For complete documentation, run: info coreutils 'wc invocation'

SHARE

This website uses cookies. By using this website you accept the use of cookies. Learn more

Got it!
RapidTables

Home > Code > Linux > ls > ls -r -R

ls -r -R command in Linux
ls -r option flag lists files/directories in reverse order.
ls -R option flag lists directory tree recursively.
 ls -r
 ls -R

ls -r
ls -r option flag lists files/directories in reverse order.

Syntax
$ ls -r [options] [file|dir]

Examples
Default list:
$ ls
Desktop Downloads Pictures Templates Videos
Documents Music Public todo.txt
$

List in reverse order:


$ ls -r
Videos Templates Pictures Downloads Desktop
todo.txt Public Music Documents
$

Long listing format in reverse order:


$ ls -lr
total 4
drwxr-xr-x 2 user user 40 2011-08-17 16:52 Videos
-rw-r--r-- 1 user user 131 2011-08-17 18:07 todo.txt
drwxr-xr-x 2 user user 40 2011-08-17 16:52 Templates
drwxr-xr-x 2 user user 40 2011-08-17 16:52 Public
drwxr-xr-x 2 user user 120 2011-08-17 18:14 Pictures
drwxr-xr-x 2 user user 40 2011-08-17 16:52 Music
drwxr-xr-x 2 user user 40 2011-08-17 16:52 Downloads
drwxr-xr-x 2 user user 40 2011-08-17 16:52 Documents
drwxr-xr-x 2 user user 80 2011-08-17 16:52 Desktop
$
Long listing format sorted by date/time in reverse order:
$ ls -ltr
total 4
drwxr-xr-x 2 user user 40 2011-08-17 16:52 Videos
drwxr-xr-x 2 user user 40 2011-08-17 16:52 Templates
drwxr-xr-x 2 user user 40 2011-08-17 16:52 Public
drwxr-xr-x 2 user user 40 2011-08-17 16:52 Music
drwxr-xr-x 2 user user 40 2011-08-17 16:52 Downloads
drwxr-xr-x 2 user user 40 2011-08-17 16:52 Documents
drwxr-xr-x 2 user user 80 2011-08-17 16:52 Desktop
-rw-r--r-- 1 user user 131 2011-08-17 18:07 todo.txt
drwxr-xr-x 2 user user 120 2011-08-17 18:14 Pictures
$

ls -R
ls -R option flag lists directory tree recursively.

Syntax
$ ls -R [options] [file|dir]

Examples
Recursive listing:
$ ls -R
.:
Desktop Downloads Pictures Templates Videos
Documents Music Public todo.txt

./Desktop:
examples.desktop ubiquity-gtkui.desktop

./Documents:

./Downloads:

./Music:

./Pictures:
ls-a.png ls-full-path.png ls-l.png ls-s.png

./Public:

./Templates:

./Videos:
$

Long listing format with recursive listing:


$ ls -lR
.:
total 4
drwxr-xr-x 2 user user 80 2011-08-17 16:52 Desktop
drwxr-xr-x 2 user user 40 2011-08-17 16:52 Documents
drwxr-xr-x 2 user user 40 2011-08-17 16:52 Downloads
drwxr-xr-x 2 user user 40 2011-08-17 16:52 Music
drwxr-xr-x 2 user user 120 2011-08-17 18:14 Pictures
drwxr-xr-x 2 user user 40 2011-08-17 16:52 Public
drwxr-xr-x 2 user user 40 2011-08-17 16:52 Templates
-rw-r--r-- 1 user user 131 2011-08-17 18:07 todo.txt
drwxr-xr-x 2 user user 40 2011-08-17 16:52 Videos

./Desktop:
total 12
-rwxr-xr-x 1 user user 203 2011-08-17 16:52 examples.desktop
-rwxr-xr-x 1 user user 7672 2011-08-17 16:19 ubiquity-gtkui.desktop

./Documents:
total 0

./Downloads:
total 0

./Music:
total 0

./Pictures:
total 556
-rw-r--r-- 1 user user 94114 2011-08-17 18:13 ls-a.png
-rw-r--r-- 1 user user 254129 2011-08-17 18:14 ls-full-path.png
-rw-r--r-- 1 user user 102761 2011-08-17 18:13 ls-l.png
-rw-r--r-- 1 user user 77374 2011-08-17 18:12 ls-s.png

./Public:
total 0

./Templates:
total 0

./Videos:
total 0
$

See also
 ls command
 ls -a
 ls -l
 ls -s
 ls -S
 ls -t
 ls full path

Write how to improve this page

LS COMMAND
 ls -a
 ls -l
 ls -r
 ls -R
 ls -s
 ls -S
 ls -t
 ls full path

RAPID TABLES

 Recommend Site
 Send Feedback
 About

Home | Web | Math | Electricity | Calculators | Converters | Tools


© 2018 RapidTables.com | About | Terms of Use | Privacy Policy

1. head Command
The head command reads the first ten lines of a any given file name. The basic syntax of head
command is:

head [options] [file(s)]

For example, the following command will display the first ten lines of the file named
‘/etc/passwd‘.
# head /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh

If more than one file is given, head will show the first ten lines of each file separately. For
example, the following command will show ten lines of each file.

# head /etc/passwd /etc/shadow

==> /etc/passwd <== root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/sbin/nologin


daemon:x:2:2:daemon:/sbin:/sbin/nologin adm:x:3:4:adm:/var/adm:/sbin/nologin lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin ==> /etc/shadow <==
root:$6$85e1:15740:0:99999:7:::
bin:*:15513:0:99999:7:::
daemon:*:15513:0:99999:7:::
adm:*:15513:0:99999:7:::
lp:*:15513:0:99999:7:::
sync:*:15513:0:99999:7:::
shutdown:*:15513:0:99999:7:::
halt:*:15513:0:99999:7:::
mail:*:15513:0:99999:7:::
uucp:*:15513:0:99999:7:::

If it is desired to retrieve more number of lines than the default ten, then ‘-n‘ option is used along
with an integer telling the number of lines to be retrieved. For example, the following command
will display first 5 lines from the file ‘/var/log/yum.log‘ file.
# head -n5 /var/log/yum.log
Jan 10 00:06:49 Updated: openssl-1.0.1e-16.el6_5.4.i686
Jan 10 00:06:56 Updated: openssl-devel-1.0.1e-16.el6_5.4.i686
Jan 10 00:11:42 Installed: perl-Net-SSLeay-1.35-9.el6.i686
Jan 13 22:13:31 Installed: python-configobj-4.6.0-3.el6.noarch
Jan 13 22:13:36 Installed: terminator-0.95-3.el6.rf.noarch

In fact, there is no need to use ‘-n‘ option. Just the hyphen and specify the integer without spaces
to get the same result as the above command.
# head -5 /var/log/yum.log
Jan 10 00:06:49 Updated: openssl-1.0.1e-16.el6_5.4.i686
Jan 10 00:06:56 Updated: openssl-devel-1.0.1e-16.el6_5.4.i686
Jan 10 00:11:42 Installed: perl-Net-SSLeay-1.35-9.el6.i686
Jan 13 22:13:31 Installed: python-configobj-4.6.0-3.el6.noarch
Jan 13 22:13:36 Installed: terminator-0.95-3.el6.rf.noarch

The head command can also display any desired number of bytes using ‘-c‘ option followed by
the number of bytes to be displayed. For example, the following command will display the
first 45 bytes of given file.
# head -c45 /var/log/yum.log
Jan 10 00:06:49 Updated: openssl-1.0.1e-16.el

2. tail Command
The tail command allows you to display last ten lines of any text file. Similar to the head
command above, tail command also support options ‘n‘ number of lines and ‘n‘ number of
characters.
The basic syntax of tail command is:

# tail [options] [filenames]

For example, the following command will print the last ten lines of a file called ‘access.log‘.
# tail access.log
1390288226.042 0 172.16.18.71 TCP_DENIED/407 1771 GET http://download.newnext.me/spark.bin? - NONE/- text/html
1390288226.198 0 172.16.16.55 TCP_DENIED/407 1753 CONNECT ent-shasta-rrs.symantec.com:443 - NONE/- text/html
1390288226.210 1182 172.16.20.44 TCP_MISS/200 70872 GET http://mahavat.gov.in/Mahavat/index.jsp pg
DIRECT/61.16.223.197 text/html
1390288226.284 70 172.16.20.44 TCP_MISS/304 269 GET http://mahavat.gov.in/Mahavat/i/i-19.gif pg
DIRECT/61.16.223.197 -
1390288226.362 570 172.16.176.139 TCP_MISS/200 694 GET http://p4-gayr4vyqxh7oa-3ekrqzjikvrczq44-if-v6exp3-
v4.metric.gstatic.com/v6exp3/redir.html pg
1390288226.402 0 172.16.16.55 TCP_DENIED/407 1753 CONNECT ent-shasta-rrs.symantec.com:443 - NONE/- text/html
1390288226.437 145 172.16.18.53 TCP_DENIED/407 1723 OPTIONS http://172.16.25.252/ - NONE/- text/html
1390288226.445 0 172.16.18.53 TCP_DENIED/407 1723 OPTIONS http://172.16.25.252/ - NONE/- text/html
1390288226.605 0 172.16.16.55 TCP_DENIED/407 1753 CONNECT ent-shasta-rrs.symantec.com:443 - NONE/- text/html
1390288226.808 0 172.16.16.55 TCP_DENIED/407 1753 CONNECT ent-shasta-rrs.symantec.com:443 - NONE/- text/html

If more than one file is provided, tail will print the last ten lines of each file as shown below.

# tail access.log error.log


==> access.log <== 1390288226.042 0 172.16.18.71 TCP_DENIED/407 1771 GET http://download.newnext.me/spark.bin? -
NONE/- text/html 1390288226.198 0 172.16.16.55 TCP_DENIED/407 1753 CONNECT ent-shasta-rrs.symantec.com:443 -
NONE/- text/html 1390288226.210 1182 172.16.20.44 TCP_MISS/200 70872 GET http://mahavat.gov.in/Mahavat/index.jsp pg
DIRECT/61.16.223.197 text/html 1390288226.284 70 172.16.20.44 TCP_MISS/304 269 GET
http://mahavat.gov.in/Mahavat/i/i-19.gif pg DIRECT/61.16.223.197 - 1390288226.362 570 172.16.176.139 TCP_MISS/200
694 GET http://p4-gayr4vyqxh7oa-3ekrqzjikvrczq44-if-v6exp3-v4.metric.gstatic.com/v6exp3/redir.html pg 1390288226.402
0 172.16.16.55 TCP_DENIED/407 1753 CONNECT ent-shasta-rrs.symantec.com:443 - NONE/- text/html 1390288226.437 145
172.16.18.53 TCP_DENIED/407 1723 OPTIONS http://172.16.25.252/ - NONE/- text/html 1390288226.445 0 172.16.18.53
TCP_DENIED/407 1723 OPTIONS http://172.16.25.252/ - NONE/- text/html 1390288226.605 0 172.16.16.55 TCP_DENIED/407
1753 CONNECT ent-shasta-rrs.symantec.com:443 - NONE/- text/html 1390288226.808 0 172.16.16.55 TCP_DENIED/407 1753
CONNECT ent-shasta-rrs.symantec.com:443 - NONE/- text/html ==> error_log <==
[Sun Mar 30 03:16:03 2014] [notice] Digest: generating secret for digest authentication ...
[Sun Mar 30 03:16:03 2014] [notice] Digest: done
[Sun Mar 30 03:16:03 2014] [notice] Apache/2.2.15 (Unix) DAV/2 PHP/5.3.3 mod_ssl/2.2.15 OpenSSL/1.0.0-fips configured -
- resuming normal operations

Similarly, you can also print the last few lines using the ‘-n‘ option as shown below.
# tail -5 access.log
1390288226.402 0 172.16.16.55 TCP_DENIED/407 1753 CONNECT ent-shasta-rrs.symantec.com:443 - NONE/- text/html
1390288226.437 145 172.16.18.53 TCP_DENIED/407 1723 OPTIONS http://172.16.25.252/ - NONE/- text/html
1390288226.445 0 172.16.18.53 TCP_DENIED/407 1723 OPTIONS http://172.16.25.252/ - NONE/- text/html
1390288226.605 0 172.16.16.55 TCP_DENIED/407 1753 CONNECT ent-shasta-rrs.symantec.com:443 - NONE/- text/html
1390288226.808 0 172.16.16.55 TCP_DENIED/407 1753 CONNECT ent-shasta-rrs.symantec.com:443 - NONE/- text/html

You can also print the number of characters using ‘-c’ argument as shown below.
# tail -c5 access.log
ymantec.com:443 - NONE/- text/html

3. cat Command
The ‘cat‘ command is most widely used, universal tool. It copies standard input to standard
output. The command supports scrolling, if text file doesn’t fit the current screen.
The basic syntax of cat command is:

# cat [options] [filenames] [-] [filenames]

The most frequent use of cat is to read the contents of files. All that is required to open a file for
reading is to type cat followed by a space and the file name.

# cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh

The cat command also used to concatenate number of files together.

# echo 'Hi Tecmint-Team' > 1

# echo 'Keep connected' > 2

# echo 'Share your thought' > 3

# echo 'connect us tecmint.com@gmail.com' > 4

# cat 1 2 3 4 > 5

# cat 5

Hi Tecmint-Team

Keep connected
Share your thought

connect us tecmint.com@gmail.com

It can be also used to create files as well. It is achieved by executing cat followed by the output
redirection operator and the file name to be created.

# cat > tecmint.txt

Tecmint is the only website fully dedicated to Linux.

We can have custom end maker for ‘cat’ command. Here it is implemented.

# cat > test.txt << end


I am Avishek
Here i am writing this post
Hope your are enjoying
end
# cat test.txt
I am Avishek
Here i am writing this post
Hope your are enjoying

Never underestimate the power of ‘cat’ command and can be useful for copying files.

# cat avi.txt

I am a Programmer by birth and Admin by profession

# cat avi.txt > avi1.txt

# cat avi1.txt

I am a Programmer by birth and Admin by profession

Now what’s the opposite of cat? Yeah it’s ‘tac‘. ‘tac‘ is a command under Linux. It is better to
show an example of ‘tac’ than to talk anything about it.
Create a text file with the names of all the month, such that one word appears on a line.

# cat month
January
February
March
April
May
June
July
August
September
October
November
December
# tac month
December
November
October
September
August
July
June
May
April
March
February
January

For more examples of cat command usage, refer to the 13 cat Command Usage
That’s all for now. I’ll be here again with another Interesting Article, worth Knowing. Till then
stay tuned and connected to Tecmint. Don’t forget to provide us with your valuable feedback in
our comment section.
SHARE

op Unix Interview Questions - Part 1


1. How to display the 10th line of a file?

head -10 filename | tail -1

2. How to remove the header from a file?

sed -i '1 d' filename

3. How to remove the footer from a file?


sed -i '$ d' filename

4. Write a command to find the length of a line in a file?

The below command can be used to get a line from a file.

sed –n '<n> p' filename

We will see how to find the length of 10th line in a file

sed -n '10 p' filename|wc -c

5. How to get the nth word of a line in Unix?

cut –f<n> -d' '

6. How to reverse a string in unix?

echo "java" | rev

7. How to get the last word from a line in Unix file?

echo "unix is good" | rev | cut -f1 -d' ' | rev

8. How to replace the n-th line in a file with a new line in Unix?

sed -i'' '10 d' filename # d stands for delete

sed -i'' '10 i new inserted line' filename # i stands for insert

9. How to check if the last command was successful in Unix?

echo $?

10. Write command to list all the links from a directory?

ls -lrt | grep "^l"

11. How will you find which operating system your system is running on in UNIX?
uname -a

12. Create a read-only file in your home directory?

touch file; chmod 400 file

13. How do you see command line history in UNIX?

The 'history' command can be used to get the list of commands that we are executed.

14. How to display the first 20 lines of a file?

By default, the head command displays the first 10 lines from a file. If we change the option of head, then we can display as many lines as we want.

head -20 filename

An alternative solution is using the sed command

sed '21,$ d' filename

The d option here deletes the lines from 21 to the end of the file

15. Write a command to print the last line of a file?

The tail command can be used to display the last lines from a file.

tail -1 filename

Alternative solutions are:

sed -n '$ p' filename

awk 'END{print $0}' filename

Recommended Reading:

1. Select Column of Characters


To extract only a desired column from a file use -c option. The following example displays 2nd character from each line of a file test.txt

$ cut -c2 test.txt

p
s

As seen above, the characters a, p, s are the second character from each line of the test.txt file.

2. Select Column of Characters using Range


Range of characters can also be extracted from a file by specifying start and end position delimited with -. The following example extracts first
3 characters of each line from a file called test.txt

$ cut -c1-3 test.txt

cat

cp

ls

3. Select Column of Characters using either Start or End Position


Either start position or end position can be passed to cut command with -c option.

The following specifies only the start position before the ‘-‘. This example extracts from 3rd character to end of each line from test.txt file.

$ cut -c3- test.txt

t command for file oriented operations.

command for copy files or directories.

command to list out files and directories with its attributes.

The following specifies only the end position after the ‘-‘. This example extracts 8 characters from the beginning of each line from test.txt file.

$ cut -c-8 test.txt

cat comm

cp comma

ls comma

The entire line would get printed when you don’t specify a number before or after the ‘-‘ as shown below.

$ cut -c- test.txt

cat command for file oriented operations.

cp command for copy files or directories.

ls command to list out files and directories with its attributes.

4. Select a Specific Field from a File


Instead of selecting x number of characters, if you like to extract a whole field, you can combine option -f and -d. The option -f specifies which
field you want to extract, and the option -d specifies what is the field delimiter that is used in the input file.
The following example displays only first field of each lines from /etc/passwd file using the field delimiter : (colon). In this case, the 1st field
is the username. The file

$ cut -d':' -f1 /etc/passwd

root

daemon

bin

sys

sync

games

bala

5. Select Multiple Fields from a File


You can also extract more than one fields from a file or stdout. Below example displays username and home directory of users who has the
login shell as “/bin/bash”.

$ grep "/bin/bash" /etc/passwd | cut -d':' -f1,6

root:/root

bala:/home/bala

To display the range of fields specify start field and end field as shown below. In this example, we are selecting field 1 through 4, 6 and 7

$ grep "/bin/bash" /etc/passwd | cut -d':' -f1-4,6,7

S-ar putea să vă placă și