SringSring

Tuesday, 7 October 2014

Unix Commands

Unixs Commands  :

File Management :
------------------------
UNIX there are three basic types of files:
Ordinary Files  :
Directories:
Special Files:
Listing Files:
ls   --> List the file and the directories in curent directory.
ls -l  --> to get more information about the listed files:
Ex  : drwxrwxr-x  2 amrood amrood      4096 Dec 25 09:59 uml
-rw-rw-r--  1 amrood amrood      5341 Dec 25 08:38 uml.jpg
First Column: represents file type and permission given on the file.                          Below is the description of all type of files.
Second Column: represents the number of memory blocks taken by the                  file or directory.
Third Column: represents owner of the file. This is the Unix user who                   created this file.
Fourth Column: represents group of the owner. Every Unix user would                 have an associated group.
Fifth Column: represents file size in bytes.
Sixth Column: represents date and time when this file was created or                    modified last time.
Seventh Column: represents file or directory name.
Hidden Files:  An invisible file is one whose first character is the dot or period character (.)
To list invisible files, specify the -a option to ls:
ls -a
Ex: .         .profile       docs     lib     test_results
..        .rhosts        hosts    pub     users
Creating Files:
vi editor to create ordinary files on any Unix system.
vi filename
Editing Files:\
vi filename
Once file is opened, you can come in edit mode by pressing key i and then you can edit file as you like.
Display Content of a File:
cat filename
This is unix file....I created it for the first time.....
I'm going to save this content in this file.
You can display line numbers by using -b option along with cat command as follows:
$ cat -b filename
Counting Words in a File:
wc filename
2  19 103 filename
First Column: represents total number of lines in the file.
Second Column: represents total number of words in the file.
Third Column: represents total number of bytes in the file. This is actual size of the file.
Fourth Column: represents file name.
Copying Files:
cp source_file destination_file
Renaming Files:
mv old_file new_file
The mv command would move existing file completely into new file. So in this case you would fine only newfile in your current directory.
Deleting Files:
$ rm filename

Standard Unix Streams:
Under normal circumstances every Unix program has three streams (files) opened for it when it starts up:

stdin : This is referred to as standard input and associated file descriptor is 0. This is also represented as STDIN. Unix program would read default input from STDIN.

stdout : This is referred to as standard output and associated file descriptor is 1. This is also represented as STDOUT. Unix program would write default output at STDOUT

stderr : This is referred to as standard error and associated file descriptor is 2. This is also represented as STDERR. Unix program would write all the error message at STDERR.

Directories :
---------------
Absolute/Relative Pathnames:
Directories are arranged in a hierarchy with root (/) at the top. The position of any file within the hierarchy is described by its pathname.
Elements of a pathname are separated by a /. A pathname is absolute if it is described in relation to root, so absolute pathnames always begin with a /.

These are some example of absolute filenames.
/etc/passwd
/users/sjones/chem/notes
/dev/rdsk/Os3
A pathname can also be relative to your current working directory. Relative pathnames never begin with /. Relative to user amrood' home directory, some pathnames might look like this:
chem/notes
personal/res
pwd  : To determine where you are within the filesystem hierarchy at any time, enter the command pwd to print the current working directory:


Listing Directories:
$ls dirname
Creating Directories:
$mkdir dirname
Removing Directories: Directories can be deleted using the rmdir command as follows:
$rmdir dirname
$rmdir dirname1 dirname2 dirname3
Renaming Directories: The mv (move) command can also be used to rename a directory. The syntax is as follows:
$mv olddir newdir

The directories . (dot) and .. (dot dot)

Unix - File Permission / Access Modes :
--------------------------------------------------
Owner permissions: The owner's permissions determine what actions the owner of the file can perform on the file.
Group permissions: The group's permissions determine what actions a user, who is a member of the group that a file belongs to, can perform on the file.
Other (world) permissions: The permissions for others indicate what action all other users can perform on the file.

The Permission Indicators:
While using ls -l command it displays various information related to file permission as follows:
$ls -l /home/amrood
-rwxr-xr--  1 amrood   users 1024  Nov 2 00:10  myfile
drwxr-xr--- 1 amrood   users 1024  Nov 2 00:10  mydir
Here first column represents different access mode ie. permission associated with a file or directory.

The permissions are broken into groups of threes,
Each position in the group denotes a specific permission,
in this order: read (r), write (w), execute (x):

The first three characters (2-4) represent the permissions for the file's owner.
For example -rwxr-xr-- represents that onwer has read (r), write (w) and execute (x) permission.

The second group of three characters (5-7) consists of the permissions for the group to which the file belongs.
For example -rwxr-xr-- represents that group has read (r) and execute (x) permission but no write permission.

The last group of three characters (8-10) represents the permissions for everyone else.
For example -rwxr-xr-- represents that other world has read (r) only permission.

File Access Modes:
The permissions of a file are the first line of defense in the security of a Unix system.
The basic building blocks of Unix permissions are the read, write, and execute permissions, which are described below:

1) Read:  --> Grants the capability to read ie. view the contents of the file.
2) Write: --> Grants the capability to modify, or remove the content of the file.
3) Execute: -> User with execute permissions can run a file as a program.

        Directory Access Modes:
Directory access modes are listed and organized in the same manner as any other file. There are a few differences that need to be mentioned:

1) Read: --> Access to a directory means that the user can read the contents. The user can look at the filenames inside the directory.
2) Write: --> Access means that the user can add or delete files to the contents of the directory.
3) Execute: --> Executing a directory doesn't really make a lot of sense so think of this as a traverse permission.

A user must have execute access to the bin directory in order to execute ls or cd command.

       Changing Permissions:
To change file or directory permissions, you use the chmod (change mode) command. There are two ways to use chmod: symbolic mode and absolute mode.

Using chmod in Symbolic Mode:
The easiest way for a beginner to modify file or directory permissions is to use the symbolic mode.
With symbolic permissions you can add, delete, or specify the permission set you want by using the operators in the following table.

Chmod operator Description
+ Adds the designated permission(s) to a file or directory.
- Removes the designated permission(s) from a file or directory.
= Sets the designated permission(s).
Here's an example using testfile. Running ls -1 on testfile shows that the file's permissions are as follows:
$ls -l testfile
-rwxrwxr--  1 amrood   users 1024  Nov 2 00:10  testfile

$chmod o+wx,u-x,g=rx testfile

Number Octal Permission Representation Ref
0 No permission ---
1 Execute permission --x
2 Write permission -w-
3 Execute and write permission: 1 (execute) + 2 (write) = 3 -wx
4 Read permission r--
5 Read and execute permission: 4 (read) + 1 (execute) = 5 r-x
6 Read and write permission: 4 (read) + 2 (write) = 6 rw-
7 All permissions: 4 (read) + 2 (write) + 1 (execute) = 7 rwx
Here's an example using testfile. Running ls -1 on testfile shows that the file's permissions are as follows:

$ls -l testfile
-rwxrwxr--  1 amrood   users 1024  Nov 2 00:10  testfile
Then each example chmod command from the preceding table is run on testfile, followed by ls -l so you can see the permission changes:

$ chmod 755 testfile
$ls -l testfile
-rwxr-xr-x  1 amrood   users 1024  Nov 2 00:10  testfile
$chmod 743 testfile
$ls -l testfile
-rwxr---wx  1 amrood   users 1024  Nov 2 00:10  testfile
$chmod 043 testfile
$ls -l testfile
----r---wx  1 amrood   users 1024  Nov 2 00:10  testfile
Changing Owners and Groups:
While creating an account on Unix, it assigns a owner ID and a group ID to each user. All the permissions mentioned above are also assigned based on Owner and Groups.

Two commands are available to change the owner and the group of files:

chown: The chown command stands for "change owner" and is used to change the owner of a file.

chgrp: The chgrp command stands for "change group" and is used to change the group of a file.

Changing Ownership:
The chown command changes the ownership of a file. The basic syntax is as follows:

$ chown user filelist
The value of user can be either the name of a user on the system or the user id (uid) of a user on the system.

Filters and Pipes :
-----------------------
The grep Command:
The grep program searches a file or files for lines that have a certain pattern. The syntax is:
$grep pattern file(s)
$ls -l | grep "Aug"
-rw-rw-rw-   1 john  doc     11008 Aug  6 14:10 ch02
-rw-rw-rw-   1 john  doc      8515 Aug  6 15:30 ch07
-rw-rw-r--   1 john  doc      2488 Aug 15 10:51 intro
-rw-rw-r--   1 carol doc      1605 Aug 23 07:35 macros
$
There are various options which you can use along with grep command:

Option Description
-v Print all lines that do not match pattern.
-n Print the matched line and its line number.
-l Print only the names of files with matching lines (letter "l")
-c Print only the count of matching lines.
-i Match either upper- or lowercase.

The sort Command:
The sort command arranges lines of text alphabetically or numerically. The example below sorts the lines in the food file:
$sort food
The sort command arranges lines of text alphabetically by default. There are many options that control the sorting:

Option Description
-n Sort numerically (example: 10 will sort after 2), ignore blanks and tabs.
-r Reverse the order of sort.
-f Sort upper- and lowercase together.
+x Ignore first x fields when sorting.

The following pipe consists of the commands ls, grep, and sort:
$ls -l | grep "Aug" | sort +4n
The pg and more Commands:
A long output would normally zip by you on the screen, but if you run text through more or pg as a filter, the display stops after each screenful of text.
Let's assume that you have a long directory listing. To make it easier to read the sorted listing, pipe the output through more as follows:
$ls -l | grep "Aug" | sort +4n | more

more?

Starting a Process:
When you start a process (run a command), there are two ways you can run it:
1) Foreground Processes
2) Background Processes

Listing Running Processes:
ps

used flags for ps is the -f ( f for full) option, which provides more information as shown in the following example:

$ps -f
UID      PID  PPID C STIME    TTY   TIME CMD
amrood   6738 3662 0 10:23:03 pts/6 0:00 first_one
amrood   6739 3662 0 10:22:54 pts/6 0:00 second_one
amrood   3662 3657 0 08:10:53 pts/6 0:00 -ksh
amrood   6892 3662 4 10:51:50 pts/6 0:00 ps -f
Here is the description of all the fileds displayed by ps -f command:

Column Description
UID User ID that this process belongs to (the person running it).
PID Process ID.
PPID Parent process ID (the ID of the process that started it).
C CPU utilization of process.
STIME Process start time.
TTY Terminal type associated with the process
TIME CPU time taken by the process.
CMD The command that started this process.

kill command to kill the process as follows:

The ping Utility:
The ping command sends an echo request to a host available on the network. Using this command you can check if your remote host is responding well or not.

The ping command is useful for the following:
Tracking and isolating hardware and software problems.
Determining the status of the network and various foreign hosts.
Testing, measuring, and managing networks.

Syntax:  $ping hostname or ip-address

The ftp Utility:
Here ftp stands for File Transfer Protocol. This utility helps you to upload and download your file from one computer to another computer.
The ftp utility has its own set of UNIX like commands which allow you to perform tasks such as:
Connect and login to a remote host.
Navigate directories.
List directory contents
Put and get files
Transfer files as ascii, ebcdic or binary
Syntax: $ftp hostname or ip-address

Few of the useful commands are listed below:

Command Description
put filename Upload filename from local machine to remote machine.
get filename Download filename from remote machine to local machine.
mput file list Upload more than one files from local machine to remote machine.
mget file list Download more than one files from remote machine to local machine.
prompt off Turns prompt off, by default you would be prompted to upload or download movies using mput or mget commands.
prompt on Turns prompt on.
dir List all the files available in the current directory of remote machine.
cd dirname Change directory to dirname on remote machine.
lcd dirname Change directory to dirname on local machine.
quit Logout from the current login.

The telnet Utility:
To connect to a remote Unix machine and work on that machine remotely.
Telnet is a utility that allows a computer user at one site to make a connection, login and then conduct work on a computer at another site.

Once you are login using telnet, you can perform all the activities on your remotely connect machine. Here is example telnet session:

C:>telnet amrood.com

The finger Utility:
The finger command displays information about users on a given host. The host can be either local or remote.

Finger may be disabled on other systems for security reasons.

1)  Write command to list all the links from a directory?
generally checking whether user knows basic use of "ls" "grep" and regular expression etc
You can write command like:
ls -lrt | grep "^l"

2)  Create a read-only file in your home directory?
chmod 400 file
3) How will you find which operating system your system is running on in UNIX?
"uname -a"

4)  How will you run a process in background? How will you bring that into foreground and how will you kill that process?
For running a process in background use "&" in command line. For bringing it back in foreground use command "fg jobid" and for getting job id you use command "jobs", for killing that process find PID and use kill -9 PID command.
5)  How do you know if a remote host is alive or not?
You can check these by using either ping or telnet command in UNIX.

6)  How do you see command line history in UNIX?
Use history command along with grep command in unix to find any relevant command you have already executed.
7)  How do you copy file from one host to other?
Many options but you can say by using "scp" command. You can also use rsync command to answer this UNIX interview question or even sftp would be ok.
8)  How do you check how much space left in current drive ?
"df" command in UNIX. For example "df -h ." will list how full your current drive is.
9)  What is the difference between Swapping and Paging?
Swapping:
Whole process is moved from the swap device to the main memory for execution. Process size must be less than or equal to the available main memory. It is easier to implementation and overhead to the system. Swapping systems does not handle the memory more flexibly as compared to the paging systems.
Paging:
Only the required memory pages are moved to main memory from the swap device for execution. Process size does not matter. Gives the concept of the virtual memory. It provides greater flexibility in mapping the virtual address space into the physical memory of the machine. Allows more number of processes to fit in the main memory simultaneously. Allows the greater process size than the available physical memory. Demand paging systems handle the memory more flexibly.

10) What is difference between ps -ef and ps -auxwww?
ps –ef command and we are wondering which process is holding the file.
ps -ef will omit process with very long command line while ps -auxwww will list those process as well.
11) How do you find how many cpu are in your system and there details?
By looking into file /etc/cpuinfo for example you can use below command:
cat /proc/cpuinfo

12)     What is difference between HardLink and SoftLink in UNIX?

13) What is Zombie process in UNIX? How do you find Zombie process in UNIX?
When a program forks and the child finishes before the parent, the kernel still keeps some of its information about the child in case the parent might need it - for example, the parent may need to check the child's exit status. To be able to get this information, the parent calls 'wait()'; In the interval between the child terminating and the parent calling 'wait()', the child is said to be a 'zombie' (If you do 'ps', the child will have a 'Z' in its status field to indicate this.)
Zombie : The process is dead but have not been removed from the process table.
14) What is "chmod" command? What do you understand by this line “r-- -w- --x?

15) In a file word UNIX is appearing many times? How will you count number?
grep -c "Unix" filename
16) How do you set environment variable which will be accessible form sub shell?
By using export   for example export count=1 will be available on all sub shell.
17) How do you find whether your system is 32 bit or 64 bit ?
        Either by using "uname -a" command or by using "arch" command.
18) There is a file Unix_Test.txt which contains words Unix, how will you replace all Unix to UNIX?
You can answer this Unix Command Interview question by using SED command in UNIX for example you can execute sed s/Unix/UNIX/g fileName.
19) You have a tab separated file which contains Name, Address and Phone Number, list down all Phone Number without there name and Addresses?
To answer this Unix Command Interview question you can either you AWK or CUT command here. CUT use tab as default separator so you can use
cut -f3 filename.

20) Your application home directory is full? How will you find which directory is taking how much space?
By using disk usage (DU) command in Unix for example du –sh . | grep G  will list down all the directory which has GIGS in Size.

21) How do you find for how many days your Server is up?
By using uptime command in UNIX.

No comments:

Post a Comment