codedecoder

breaking into the unknown…

linux command with examples

15 Comments

I am using Ubuntu for last 5 years and doing a lot of things from command line. Many of the day to day command is now on my tip, but many of more I have used is out of my mind, and I have to google it back, So I have decided to note it down here for my future reference. I will keep adding to it whenever I get time or use new command.

Note : 

Linux command can take a no of options. These options can be passed in both shorthand form or expanded form. with shorthand form use single hyphen – and with expanded form use double hyphen –  -, say you can get help option to a command as -h or – -h

Some options do not need any argument while other need some argument to be passed with them. you can pass all the options separately, but it is better to pass argument less options grouped together and passing option with argument separately. Say,  $ mkdir -pv -m 777 myfolder is more concise then $ mkdir -p -v -m 777 myfolder. In the first case we have grouped -p -v together as -pv. Since -m option need further argument here we have passes 777, we have kept it separate from -pv

| , known as pipe is very important for filtering result when used with grep. | basically, pass the result of first function as a block to the next function. Example,  ls | grep myfile will list only those files and folder which have myfile in there name. Here ls will return list of all file and folders which will passed to grep, which will do the filtering.

1 -> history # will show you all the command you have typed in past

Syntax : history #it do not take any argument

Example:

$ history # will list all comand used in past

$ history | grep netbeans # since we have piped the result of history to grep it will return only those command , which contain word history in them

2 -> man #show complete detail of a command

syntax : man command_name

It is basically short form of manual and will tell you detail about other commands you pass to it as argument. It will explain you what that particular command do, how it work, what options it will take and so on. Basically, if you remember name of any command, you can get all detail of it with man command.

Example

$ man man # it will tell about how to use man itself

$ man sudo # will tell you all about sudo command

$ man dpkg # will tell you all about dpkg command

3 -> help #show tha available options for a command

Syntax: command_name – -help or command_name -h

unlike man , it will just tell you about different options a command can take. Since, most of the time we are most concerned about the available options a command can take rather then the whole detail, It is used more often then the man command. Also, most of the software , say netbeans comes with help option which will help you on how to execute them. On other hand man will work only with ubuntu command.

NOTE : If you know name of a command, you can get all available options with -h or - -help option. Remember that for some command -h not work but you have to pass - -help. for example:  rm -h will not work, you have to use rm – -help to know about rm options

Example:

$ cd /netbeans-6.9.1/bin #move to netbeans bin directory

$ ./netbeans – -help # you want to start netbeans and want to know available options. It has listed down all options for you
General options:
  –help                          show this help
  –jdkhome <path>      path to Java(TM) 2 SDK, Standard Edition
  -J<jvm_option>        pass <jvm_option> to JVM

  –cp:p <classpath>    prepend <classpath> to classpath
  –cp:a <classpath>    append <classpath> to classpath

4  -> ls # Listing files and folders

Syntax : ls [options] #options are optional, if you do not pass it will take the default, you can see complete list of options

with ls – -help

Examples:

$ ls #will list all folder and files but not hidden files or folder

$ ls -a # will list hidden files and folders also

$ ls -B #will not list the backup file ending with ~

$ ls -l # will do complete listing with all details like owner, date, permission etc. but will not show hidden file

$ ls -l -a -B #will do all the above

5 -> mkdir # creating directory

Syntax: mkdir [options] directory_name #options are optional, if you do not pass it will take the default, you can see list of options with mkdir – -help

Example:

$ mkdir myfolder

$ mkdir -p myfolder1/myfolder2/myfolder3 # -p option tell to create nested directory with parent child relation. Thus myfolder3 will be created in myfolder2 and so on

$ mkdir -p myfolder# the p option means parent , if the directory already exist do not throw error but use the existing directory as parent

$ mkdir -pv -m 777 myfolder # it will not complain if directory exist, set the permission to 777 and also print the task it performing on terminal

6 -> cd #changing directory

Syntax : cd directory_name # you can pass directory_name or .. or ~ to cd

Examples:

$ cd myfolder # take you inside myfolder

$ cd .. # take you out from current folder to the previous folder

$ cd ~ # take you out of every previous folder to the root of terminal

7-> touch # it will create a file if not present and if already present will modify its modification or access time depending on argument you pass to it, but not overwrite its content

Syntax : touch [options] file_name # touch –help will show you all available option. If you do not pass any option you can create multiple file with single touch command

Examples :

$ touch test1 #will create test1 file

$ touch test1 test2 test3 test4 # will create test2 test3 test4 as new file. Since test1 is already there it will just modify its access time

$ touch -a test1 # will change access time of test1 file

$ touch -m test1 # will change modification time of file test1

$ touch -am test1 # will change both access as well as the modification time

$ touch -d '1 May 2005 10:22' test1 # with d option you can set any date you want but maintain the formate of string, say '1 05 2005 10:22' otherwise '2005 1 May 10:22' will give error. however, you can ignore time if you want

$ touch -d '1 May 2005' test1 # it will set only the date, if you do not pass year then it will take current year i,e '1 May' will also work

$ touch -r test2 test1 # -r is reference option i,e it will set datetime of file test2 to test1 file

8 -> rm # removing file or folder, by default it remove only files to remove a folder, you need to pass additional options

Syntax: rm [options] file_or_directory_name #options are optional, if you do not pass it will take the default, you can see list of options with rm – -help

Example :

$ rm my_file # will remove my_file

$ rm -f my_file # will not throw error if my_file do not exist i,e it will ignore the removal

$ rm -fi my_file # Will ignore if file is not there and ask you to press Y to delete the file i,e it will become interactive

$ rm -r my_folder # The -r option must be passed to delete a folder other while it will not delete it

$ rm -rf my_folder # will delete the folder and will not complain if the folder do not exist

9 -> rmdir #it will list empty directory

Syntax : rmdir [options] directory_name # without argument it will delete all empty directory name passed to it. It will throw error if directory is not empty. for that case use rm as above

Examples:

$ rmdir dir1 dir2 dir3 # it will delete the empty directory dir1 dir2 dir3

$ rmdir -p dir1/dir2/dir3/dir4 # It will delete the parent also if deleting the child make it empty, so first dir4 will be deleted then dir3 then dir2 and so on

10 -> mv # It will move file or directory to other location. if the location of source destination is same the file or directory will be get renamed

Syntax: mv [options] source destination # If two files are provided as source and destination source will be renamed as destination. If you pass more then two argument and the last one is directory all the previous will be treated as source and will be moved into the last directory, but if the last argument is not directory it will throw error.

Examples :

$ mv myfile.txt myfile.rb # it will rename myfile.txt to myfile.rb i,e the name is changed.

$ mv -bvi myfile.txt myfile.rb # here we are passing some option b will backup the file before renaming, i will ask your yes no before renaming and v will print what going on the console

$ mv test1 test_folder myfile.rb /home/arun/my_folder # it will move the file test , myfile.rb and the test_folder to /home/arun/my_folder

$ mv *  /home/arun/my_folder # it will move everything in current folder to /home/arun/my_folder

11-> grep # It is used to search a pattern specified by user in the given text or files or block passed from first command to it through the pipe symbol |

Syntax: grep [options] pattern [files] # the complete list of options can be accessed with grep – -help command. If you want to match more than one word pass  within ” “

$ grep “Linux is good” file1 file2 file3 # It will list all lines of these three file containing “Linux is good” in it in separate line, each line will be preceded with name of the file in which they appear. If you do not want the file name you can use -h option as below

$ grep -h “Linux is good” file1 file2 file3 # It will not precede the matched line with the file in which they are found

$ grep -i “Linux is good” file1 file2 file3 # it tell to ignore the case i,e “linux is good” will also match

$ grep “Linux is good” * #will search the text “Linux is good” in all the text file in the current directory

$ grep -r “Linux is good” * #-r option will make it to search the text “Linux is good” in all the text file recursively in the current directory as well as all it child directory

$ grep -c “Linux is good” file1 file2 # It will not print each line but just return the count of match in each file

$ grep -n “Linux is good” file1 file2 # It will also print the line number of the line containing the pattern in each file

$ grep -rni “Linux is good” * # will recursively search each directory, print the line no and will ignore the case

$ ls -l | grep “foo” # it will list only those file and directory which containn the word foo

$ history | grep rails # will list history of only those command which contain the word rails

$ history | grep -in rails #will ignore case,  and print line no.

12 -> less # can be used to see content of a file .It allow you to display a large data in block and let you to scroll down, basically, it keep the screen at first line and let you scroll down. If you do not use this, screen will set to the last line and you have to scroll up to see the first line. you can exit the content by pressing q .

Syntax : less [options] file_name # you can see complete list of option with less – -help. Though, generally, I used it to see the content of file or a command from top and have not tried any options .

Examples:

$ less myfile.txt # It will show content of file from the top, need to scroll down to see more content. press q to exit the content

$ ps -ef | less #will show the result of ps -ef command from the top

13 -> more # It can be also used to display content of a file on terminal.

syntax: more [options] file_name # By default It do not provide scroll down facility like less to see the whole content but show only that much content which fit into your screen. however, using different options you can set the no of line you want to see, which will activate the scrolling if the set line not come on the screen

Examples:

$ more myfile # will show that much content of file which fit in screen

$ more -100 + 50 myfile # will show 100 lines of file starting from line 50

$ more +/”Iam arun” -100 # will show 100 line of the file from the line which contain “Iam arun”

$ more -s -u -100  +50 myfile #  s will cause to remove blank line from display and u will remove underlines

$ ps -ef | more -10 + 20 # will display 10 lines of the result of command ps -ef starting from the 20 line

14 -> cat # will be used to create a file, read a file, concenate content of many files

syntax : cat [options] [input_filename] [> or >>] [output_filename] # all the things in [] is optional i,e cat can work without them also

NOTE :

1 -> If you do not provide output_filename the output will be printed on terminal itself i,e terminal is the standard output for cat command

2 -> > and >> both are called append operator i,e write content to a file but > will erase the file of content if exist and write to it but >> will add the new content to the existing content , so it is safer to use >> instead of>

Example:

$ cat >> test_file1 # it will create test_file1 and when you press enter it will take you to the next line where you write to it, to exist press enter then press ctrl and d
I have pressed enter on last line to reach here
again pressed eneter to come to next line and keep writing
All content Iam writing will get written to test_files1                                 
to exist writing we will press Enter followed by Ctrl D

$ cat test_file1 # it will show you content of file test_file1, so you can see the content you have written on the terminal
I have pressed enter on last line to reach here
again pressed eneter to come to next line and keep writing
All content Iam writing will get written to test_files1
to exist writing we will press Enter followed by Ctrl D

arun@arun-yadav:~$ cat -n test_file1 #the -n option will print the line no also
  1    I have pressed enter on last line to reach here
     2    again pressed eneter to come to next line and keep writing
     3    All content Iam writing will get written to test_files1
     4    to exist writing we will press Enter followed by Ctrl D

$ cat >> test_file2 # will create a new file
This is the second file # you added this line to test_file2

$ cat test_file1 test_file2 >> test_file3 # will create file test_file3 and append content of test_file1 test_file2 to it

$ cat test_file3 # it show the content of test_file3, you can see that this file contain content of both the files
I have pressed enter on last line to reach here
again pressed eneter to come to next line and keep writing
All content Iam writing will get written to test_files1
to exist writing we will press Enter followed by Ctrl D
This is the second file

15 -> echo # you can use it to write a string to file or terminal itself

syntax: echo string [filename] # file name is optional if you do not pass it the output will be printed to the terminal

unlike cat, it can use to write single string to a file or terminal i,e you can write multiple lines as with cat command

Example:

$ echo Iam Arun # it will print the output to terminal
Iam Arun
$ echo Iam Arun to test_file >> test_file # it will append the string to the test_file, if test_file is not present >> operator will create it and the append to it
$ cat test_file # we will see the content of test_file
Iam Arun to test_file
$ echo Iam adding one more line >> test_file # one more line is appended
$ cat test_file # you can see both the line
Iam Arun to test_file
Iam adding one more line
$ echo this “>” operator is dangerous as it will erase and write > test_file # see the danger of using >, if the file exist it will erase its content before appending
arun@arun-yadav:~$ cat test_file
this > operator is dangerous as it will erase and write # see earlier line is erased and only single line present

16 -> pstree # will return all the running process in tree structure with there name and process id

Syntax : pstree [options] [pid or username] # you can see the  complete list of option with  pstree – -help. the argument is user or process_id whose tree you want to see

Example:

$ pstree #will list all the running process with all the user

$ pstree root # will show all the process running with root user

$ pstree arun # will list all the process running with the user arun

$ pstree -p arun # will print the PID i,e process id also with the name

$ pstree -pn  # will print the PID and also in the sorted order

$ pstree -pnh # the h option will highlight the current running process

$ pstree -pnhu # the u option will also print the user owning that process

$ pstree -pnhul # l option will not allow to truncate the process detail if it is too long

17 -> pgrep # It will return PID of the process

Syntax : pgrep process_name # it will return the PID of process_name. It will be helpful if you know the process name otherwise use pstree or ps to find PID

Examples:

$ pgrep firefox # will return PID of firefox

$ pgrep ruby # will return PID of ruby

$ pgrep skype # will return PID of skype

18 -> ps # it means process status and return all the running process with name and PID

Syntax :  ps [options] # you can see all the available options with ps – -help

Examples :

$ ps # will return currently active process

$ ps -e # will return all the running process

$ ps -ef # will return all running process with full detail

$ ps -ef | less # as process list is very long, we have piped the output of ps -ef to less command. It help you to display result in small blocks and let you to scroll down to see more

19 -> pkill # will kill the process passed to it

Syntax: pkill process_name # It would be helpful only if you know the name of process, you want to kill

Examples:

$ pkill ruby

$ pkill firefox

20 -> kill # will kill the process whose PID is passed to it

syntax : kill [signals] PID # there is 60 type of signal which can be passed to kill, but you have to just remember 9 which is called SIGKILL, the default signal passed is 15 which is called SIGTERM. Actually, kill do not kill the process itself instead, it just pass proper signal to a process which cause it to terminate i,e logic of termination is in every process itself. Say, for example when you close firefox browser, signal 9 get passed to the firefox process by our OS and it get terminated. The kill command just give you a way to pass signal to a process from the terminal.Thus by passing proper signal with kill you can control any state of a process. But mostly that is not needed. Mostly it is use to close any hanged process. If any process get hanged, you get its PID from the above pstree or pgrep or ps command and the pass it to kill to terminate that hanged process.

NOTE: the complete list of signal available for kill can be listed with kill -l

Examples:

$ kill 485 #will terminate the process with PID 485. here the default signa 15 get passed, there may be chance that it fail to kill the process, say if it is making some system call

$ kill -9 485 # it will be guaranteed that the process will be called. If the process is making any system call, it will wait and kill it when it return from the call

21 -> killall #will kill the process along with its child whose name passed to it. helpful if you know the process name

syntax: killall [options] process_name #will kill the process and all its child

NOTE: Killing by file name only works for executables  (i.e., runnable programs) that are kept open during execution

Examples:

$ killall nautilus #will kill the nautilus process

$ killall -e nautilus # it will tell to kill whose name exactly match with nautilus. It will be helpful if your process name is more that 15 character, since killall by default match only upto that, so will delete all other process also whose first 15 character matches. the -e option will prevent this.

$ killall -ew nautilus # the w option will tell to wait till all the process are killed, otherwise killall check it every second by default and resend the signal if found some is still running, but since some has already get  killed, some signal become unresponsive. Also killall can kill all the process, including other killall process, except itself

22 -> pwd # will print the current working directory

23 -> clear # It will remove all previous command and output from the console

24->SCP # You can take it as server copy. scp command is used to copy files from one server to other.It can be from your local machine to some  other machine or vice versa. You can also use it to copy file between two different machine from your system.

Below will be the syntex :

CASE 1: Copy file from from your system to some other system:
scp  /path/to/local/file  username@hostname:/path/to/remote/file

CASE 2: Copy file from another system to your system:

scp  username@hostname:/path/to/remote/file  /path/to/local/file

CASE 3: Copy file from some system to some other system from your machine:

scp  username1@hostname1:/path/to/file  username2@hostname2:/path/to/other/file

NOTE : username@hostname is basically the url to which you ssh

24-> lscpu

This will tell you information about your CPU. Like you may want to know, you are having 32 bit or 64 bit processor (remember many a time at the time of download you do not know you should download 32 or 64 bit version).

Example :

$ lscpu
Architecture:                          i686
CPU op-mode(s):                   32-bit, 64-bit
Byte Order:                           Little Endian
CPU(s):                                   4
On-line CPU(s) list:              0-3
Thread(s) per core:              2
Core(s) per socket:               2
Socket(s):                              1
Vendor ID:                          GenuineIntel
CPU family:                         6
Model:                                 42
Stepping:                             7
CPU MHz:                           3092.905
BogoMIPS:                         6185.90
Virtualization:                     VT-x
L1d cache:                           32K
L1i cache:                            32K
L2 cache:                             256K
L3 cache:                             3072K

Architecture showing to be i686(X86, i686, or i386 is same), which means your OS is of 32 bit. But the CPU op-mode showing that it can work in both 32 and 62 bit mod i,e your CPU is of 64 bit. So if you want you can install 64 bit Ubuntu OS on it, but if the mode is only 32 bit, you can’t

NOTE :

X86, i686, or i386      means you are running a 32 bit kernel i,e OS.
X86_64 , amd64 , or X64 means you are running a 64 bit kernel i,e OS.

24->Complete Listing

Complete list of Linux command with detailed explanation is available here.

Reference :

http://www.linfo.org/pipes.html

About these ads

Author: arunyadav4u

over 5 years experience in web development with Ruby on Rails.Involved in all stage of development lifecycle : requirement gathering, planing, coding, deployment & Knowledge transfer. I can adept to any situation, mixup very easily with people & can be a great friend.

15 thoughts on “linux command with examples

  1. Thanks. Much appreciated.

  2. what is the meanig of this command:
    #trig ‘c’ “lpg”

  3. cmd file*|file1 works ?

  4. gen. we use cmd 1| tee newfile | cmd2 for “tee”

    will it work as following:

    cmd1| cat >file | cmd2

    can u help me in this I was in a confusion with the cmd

    • Satish,

      You are trying to use pipe command of linux.It pass the output of previous command as input to the second command. Here, you should note that the second command will process the output given by first command only if it except block to process on, otherwise it will do what it ought to do independently.
      hope below example will clear it:

      let us create a sample file for demo with some content from terminal.

      $ cat >> demo_to_satish
      arun in first line
      satish in second line
      arun in third line

      So now we have demo_to_satish file with three lines written to it. Now let us see use of pipe command over it

      $ cat demo_to_satish | grep arun
      arun in first line
      arun in third line

      we know cat command output the content of file, so the output is passed to grep command which will return lines containg arun from the block passed to it. So the block required by grep to process on is coming from cat command.

      $ cat demo_to_satish | sort
      arun in first line
      arun in third line
      satish in second line

      So this time be passed the output to sort command which return the lines in ascending order. see that second line is actually printed last as expected from sort command

      $ cat demo_to_satish | sort | grep -n arun
      1:arun in first line
      2:arun in third line

      So here, we have piped three command, since sort, grep command except block of code, the process the previous output.
      Now see this
      $ cat ajay.txt
      This file is created by ajay
      $ cat demo_to_satish | sort | grep -n arun | cat >> ajay.txt | cat ajay.txt
      This file is created by ajay
      $ cat ajay.txt
      This file is created by ajay
      1:arun in first line
      2:arun in third line

      So, you can see that ajay.txt file initially have a single line. In the second command we have used 4 pipe, first output the content of demo_to_satish which is the sorted, then grep takeout only those line containing arun, this output is then passed to ajay.txt file through cat >> and then last one try to print the final content of ajay.txt file. But what is this it printed only initial line of ajay.txt. So is the previous cat command didn’t worked. It worked as you can see from the last command which print all the line. actually cat >> come into affect only after exit.

  5. sir can u provide a advance shell scripting command

    • Dhiraj,

      There is nothing like advance shell scripting command. The command you see in the above post can be also used in shell scripting. shell scripting is basically a programming language which allow you to write system program. for example : below is a small script which clear system log.

      create a file say clear_log.sh and put below line to it

      #!/bin/bash
      LOG_DIR=/var/log
      cd $LOG_DIR
      cat /dev/null > messages
      cat /dev/null > wtmp
      echo "Logs cleaned up."
      exit

      Now when you go to your terminal and run below command, it will clear the log

      $ sudo sh clear_log.sh
      Logs cleaned up.

      you need to run any shell program as root user so we used sudo. sh is the command which will execute your file containing the script.

      There is a number of ebook and tutorial available online to write shell script. I suggest you to go through this .

      If I get time, I will try to write a post on basics of shell scripting.

      • I didn’t find any site where any freshers can learn Linux command by his-self and in very simple language .Could you explain or mention any link as go through illustrating the above commands.Whatever command you explained are clear to me.So please explain all others too.

      • pooja,

        There is a number of pdf available online which you can download and read to learn and understand the commands.You can search google for “linux command pdf”, it will list a number of link for you. I have gone through few of them for you and find this (click here to download) one as worth reading.

        If you want to become a linux professional I suggest you to buy some book like LINUX COMPLETE REFERANCE or LINUX COMMAND LINE AND SCRIPTING BIBLE

        As far as my above post is concerned, I am glad to know that you have find it useful. Actually I have learned them not in a day but over the years :)

        I will keep adding to it as I come through and use some new command

  6. How to get per IP volume send from the mail server, do we have specific command where I can retrieve this information, Look forward for your suggestions.

  7. Thanks a lot….Must be more elaborate and provide online linux console to test commands.

  8. Dear Sir , I don’t understand about grep command plz add some easy examples.

    • in simple words, grep filter the item from the list passed to it

      Try this.

      say you want to know process ID of skype, you are loged in on your system.

      You can run below command to get the process ID

      $ ps -ef

      But above command will return 100 of item. Now you do not want to go through all of them to find skype.
      Here come grep at your rescue. Try below

      $ ps -ef | grep skype

      It will return only the item containing skype word in it.

      here grep will take the output of first command before the pipe | and find those records which contain skype word in it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.