Wednesday, February 23, 2011

Linux/Unix Common Commands

Hey
Here I am going to review some useful Linux commands. As we are Java programmer and JDK is compatible in most platforms and since most of server platforms are Linux base, so we should know how to work with them. there are some common commands which we need them like copy, cut, remove, service stop, show processes and so on.
I am not going to teach Linux and Linux core. Here I prepare you as a simple user of Linux.
OK let's start:
Note: You can use --help in front of any following command to display help of the specified command. But some practical switches will be available here.
Example: ls --help
Result:
Usage: ls [OPTION]... [FILE]...
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuvSUX nor --sort.

Mandatory arguments to long options are mandatory for short options too.
  -a, --all                  do not ignore entries starting with .
  -A, --almost-all           do not list implied . and ..
      --author               with -l, print the author of each file
  -b, --escape               print octal escapes for nongraphic characters
      --block-size=SIZE      use SIZE-byte blocks
  -B, --ignore-backups       do not list implied entries ending with ~
  -c                         with -lt: sort by, and show, ctime (time of last
                               modification of file status information)
                               with -l: show ctime and sort by name
                               otherwise: sort by ctime
  -C                         list entries by columns
      --color[=WHEN]         control whether color is used to distinguish file
                               types.  WHEN may be `never', `always', or `auto'
  -d, --directory            list directory entries instead of contents,
                               and do not dereference symbolic links
  -D, --dired                generate output designed for Emacs' dired mode
  -f                         do not sort, enable -aU, disable -lst
  -F, --classify             append indicator (one of */=>@|) to entries
      --file-type            likewise, except do not append `*'
      --format=WORD          across -x, commas -m, horizontal -x, long -l,
                               single-column -1, verbose -l, vertical -C
      --full-time            like -l --time-style=full-iso
  -g                         like -l, but do not list owner
  -G, --no-group             like -l, but do not list group
  -h, --human-readable       with -l, print sizes in human readable format
                               (e.g., 1K 234M 2G)
      --si                   likewise, but use powers of 1000 not 1024
  -H, --dereference-command-line
                             follow symbolic links listed on the command line
      --dereference-command-line-symlink-to-dir
                             follow each command line symbolic link
                             that points to a directory
      --hide=PATTERN         do not list implied entries matching shell PATTERN
                               (overridden by -a or -A)
      --indicator-style=WORD append indicator with style WORD to entry names:
                               none (default), slash (-p),
                               file-type (--file-type), classify (-F)
  -i, --inode                with -l, print the index number of each file
  -I, --ignore=PATTERN       do not list implied entries matching shell PATTERN
  -k                         like --block-size=1K
  -l                         use a long listing format
  -L, --dereference          when showing file information for a symbolic
                               link, show information for the file the link
                               references rather than for the link itself
  -m                         fill width with a comma separated list of entries
  -n, --numeric-uid-gid      like -l, but list numeric user and group IDs
  -N, --literal              print raw entry names (don't treat e.g. control
                               characters specially)
  -o                         like -l, but do not list group information
  -p, --indicator-style=slash
                             append / indicator to directories
  -q, --hide-control-chars   print ? instead of non graphic characters
      --show-control-chars   show non graphic characters as-is (default
                             unless program is `ls' and output is a terminal)
  -Q, --quote-name           enclose entry names in double quotes
      --quoting-style=WORD   use quoting style WORD for entry names:
                               literal, locale, shell, shell-always, c, escape
  -r, --reverse              reverse order while sorting
  -R, --recursive            list subdirectories recursively
  -s, --size                 with -l, print size of each file, in blocks
  -S                         sort by file size
      --sort=WORD            extension -X, none -U, size -S, time -t,
                             version -v, status -c, time -t, atime -u,
                             access -u, use -u
      --time=WORD            with -l, show time as WORD instead of modification
                             time: atime, access, use, ctime or status; use
                             specified time as sort key if --sort=time
      --time-style=STYLE     with -l, show times using style STYLE:
                             full-iso, long-iso, iso, locale, +FORMAT.
                             FORMAT is interpreted like `date'; if FORMAT is
                             FORMAT1<newline>FORMAT2, FORMAT1 applies to
                             non-recent files and FORMAT2 to recent files;
                             if STYLE is prefixed with `posix-', STYLE
                             takes effect only outside the POSIX locale
  -t                         sort by modification time
  -T, --tabsize=COLS         assume tab stops at each COLS instead of 8
  -u                         with -lt: sort by, and show, access time
                               with -l: show access time and sort by name
                               otherwise: sort by access time
  -U                         do not sort; list entries in directory order.
                             In combination with one_per_line format `-1',
                             it will show files immediately and it has no
                             memory limitations.
  -v                         sort by version
  -w, --width=COLS           assume screen width instead of current value
  -x                         list entries by lines instead of by columns
  -X                         sort alphabetically by entry extension
  -1                         list one file per line

SELinux options:

      --lcontext             Display security context.   Enable -l. Lines
                               will probably be too wide for most displays.
      -Z, --context          Display security context so it fits on most
                               displays.  Displays only mode, user, group,
                               security context and file name.
      --scontext             Display only security context and file name.


      --help     display this help and exit
      --version  output version information and exit

SIZE may be (or may be an integer optionally followed by) one of following:
kB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.

By default, color is not used to distinguish types of files.  That is
equivalent to using --color=none.  Using the --color option without the
optional WHEN argument is equivalent to using --color=always.  With
--color=auto, color codes are output only if standard output is connected
to a terminal (tty).  The environment variable LS_COLORS can influence the
colors, and can be set easily by the dircolors command.

Exit status is 0 if OK, 1 if minor problems, 2 if serious trouble.

Report bugs to <bug-coreutils@gnu.org>.


  1. pwd: To show the current directory where you are in. you can use this command any where.
    Example: [root@testserver ~]# pwd
    Result: /root
  2. clear: To clear the screen.
    Example: [root@testserver ~]# clear
    Result: [root@testserver ~]#
  3. cd: To change the current directory to specified directory.
    1. cd /: return to the root path
    2. cd ..: return to the upper directory
    3. cd .: return to the current directory
    Example: [root@testserver ~]# cd /opt/data
    Result: [root@testserver data]#
  4. ls: To list the directory content.
    1. ls -list: lists the directory content in detail like creation time, size and so on.
    2. ls -f: does not sort.
    3. ls | grep a: lists the directory content containing 'a' in their name
  5. cp source destination: To copy source to destination.
    Example: [root@testserver opt]# cp test.cnf /root/test.cnf
    Result: copies test.cnf from current directory(/opt) to /root directory
  6. cp -r source destination: To copy source directory to destination.
    Example: [root@testserver opt]# cp -r data /root/data2
    Result: copies data folder to /root directory in new name (data2)
  7. mv source destination: To cut(move) source to destination. you can also use it to rename a directory or file.
    Example: [root@testserver opt]# mv data data2
    Result: renames data directory to data2
  8. rm filename: To remove file with specified filename
    Example: [root@testserver opt]# rm /root/test.cnf
    Result: removes test.cnf in /root path
  9. rm -rf directoryname: To remove directory and all containing files and sub-directories recursively(r) without prompting(f)
    Example: [root@testserver opt]# rm -rf /root/data2
    Result: remove data2 directory and all its containing data from /root path
  10. ps aux: To list the running system processes in detail like cpu usage, memory usage, process id and so on.
    Example: [root@testserver opt]# ps aux
    Result:
    USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
    root         1  0.0  0.0  10348   548 ?        Ss   Jan11   0:01 init [5]
    root         2  0.0  0.0      0     0 ?        S<   Jan11   0:00 [migration/0]
    root         3  0.0  0.0      0     0 ?        SN   Jan11   0:00 [ksoftirqd/0]
    root         4  0.0  0.0      0     0 ?        S<   Jan11   0:00 [watchdog/0]
    root         5  0.0  0.0      0     0 ?        S<   Jan11   0:00 [migration/1]
    root         6  0.0  0.0      0     0 ?        SN   Jan11   0:00 [ksoftirqd/1]
    root         7  0.0  0.0      0     0 ?        S<   Jan11   0:00 [watchdog/1]
    root         8  0.0  0.0      0     0 ?        S<   Jan11   0:00 [migration/2]
    root         9  0.0  0.0      0     0 ?        SN   Jan11   0:00 [ksoftirqd/2]
    ...
  11. ps aux | grep somthing: To Filter the list of processes to specified name. It searches in processes detail and variables by specified name and show you in details.
    Example: [root@testserver opt]# ps aux | grep tomcat
    Result:
    root      5593  0.0  9.3 1460380 370892 ?      Sl   Feb19   3:38 /opt/jdk1.6.0_07/bin/java -Djava.util.logging.config.file=/opt/apache-tomcat-6.0.18/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Xms256m -Xmx1024m -XX:MaxPermSize=256m -Djava.endorsed.dirs=/opt/apache-tomcat-6.0.18/endorsed -classpath /opt/apache-tomcat-6.0.18/bin/bootstrap.jar -Dcatalina.base=/opt/apache-tomcat-6.0.18 -Dcatalina.home=/opt/apache-tomcat-6.0.18 -Djava.io.tmpdir=/opt/apache-tomcat-6.0.18/temp org.apache.catalina.startup.Bootstrap start
    root     22672  0.0  0.0  61180   744 pts/5    S+   12:04   0:00 grep tomcat

  12. kill -9 PID: To kill the process with specified PID. you can find PID by ps command then use this command to kill it.
    Note: PID is not fix for processes. A new PID will be assign any time you run some process so you should first catch it by ps command.
    Example: [root@testserver opt]# kill -9 5593
    Result: kills process with id of 5593(tomcat process)
  13. unzip zipfilename: To unzip the zipped file.
    Example: [root@testserver opt]# unzip test.zip
    Result: unzips the test.zip file.
  14. execute a process: you should just write the executive file with its path then press enter to start it. if you want to start it in background of the shell put '&' sign in front of the file name
    Example: [root@testserver bin]# ./catalina.sh run &
    Result: executes catalina.sh in back ground with run switch(the needed parameter of this file). if you don't specify '&' sign it shows you in the current shell and you will not able to write a new command. so you should first stop it. In this state (running the process in current shell) press Ctrl + c to stop it. But if you run it in background, you should kill this process to stop it.
  15. service  --status-all: To list the current services and their status.
    Example: [root@testserver opt]# service  --status-all
    Result:
    acpid (pid 2410) is running...
    anacron is stopped
    atd (pid  2627) is running...
    auditd (pid  2138) is running...
    automount (pid 2476) is running...
    Avahi daemon is running
    Avahi DNS daemon is not running
    hcid (pid 2330) is running...
    sdpd (pid 2336) is running...
    capi not installed - No such file or directory (2)
    conmand is stopped
    cpuspeed is stopped
    crond (pid  2581) is running...
    cupsd (pid  2520) is running...
    cups-config-daemon is obsolete
    dnsmasq is stopped
    dund is stopped
    Usage: /etc/init.d/firstboot {start|stop}
    gpm (pid  2572) is running...
    hald (pid 2419) is running...
    hidd (pid 2453) is running...
    hpiod (pid 2493) is running...
    hpssd (pid 2498) is running...
    Firewall is stopped.
    ipmi_msghandler module not loaded.
    ipmi_si module not loaded.
    ipmi_devintf module not loaded.
    /dev/ipmi0 does not exist.
    Firewall is stopped.
    irattach is stopped
    irqbalance (pid 2220) is running...
    Kdump is not operational
    krb524d is stopped
    mcstransd (pid 1904) is running...
    mdadm is stopped
    mdmpd is stopped
    dbus-daemon (pid 2308) is running...
    multipathd is stopped
    mysqld (pid 21367) is running...
    netconsole module not loaded
    netplugd is stopped
    Configured devices:
    lo eth0
    Currently active devices:
    lo eth0
    NetworkManager is stopped
    rpc.mountd is stopped
    nfsd is stopped
    rpc.rquotad is stopped
    rpc.statd (pid  2269) is running...
    nscd is stopped
    ntpd is stopped
    pand is stopped
    pcscd (pid  2400) is running...
    portmap (pid 2231) is running...
    Process accounting is disabled.
    rdisc is stopped
    restorecond (pid  2157) is running...
    rpc.idmapd (pid 2293) is running...
    saslauthd is stopped
    sendmail (pid  2553) is running...
    setroubleshootd (pid  2320) is running...
    smartd (pid 2719) is running...
    openssh-daemon (pid  2511) is running...
    syslogd (pid  2166) is running...
    klogd (pid  2169) is running...
    Xvnc is stopped
    wdaemon is stopped
    winbindd is stopped
    wpa_supplicant is stopped
    xfs (pid  2610) is running...
    xinetd (pid  2534) is running...
    ypbind is stopped
    yum-updatesd (pid 2850) is running...
  16. service servicename [stop|start|restart]: To stop or start or restart the service with specified service name.
    Example: [root@testserver opt]# service mysqld restart
    Result:
    Stopping MySQL:                                            [  OK  ]
    Starting MySQL:                                            [  OK  ]
  17. vi filename: To edit or even create (if not exist) a file content. It opens the specified file in editor. you can first view it. but if you are going to change it, press Insert key on your keyboard then you can change it. after changing:
    1. Esc then ":w" then Enter: will save the file.
    2. Esc then ":q" then Enter: will quit the editor.
    3. Esc then ":wq" then Enter: will save the file and quit the editor.
    4. Esc then ":q!" then Enter: will quit editor without saving the file.
  18. free: To show memory status like total size, free space and so on.
    Example: [root@testserver opt]# free
    Result:
                 total       used       free     shared    buffers     cached
    Mem:       3979020    3642384     336636          0     256836    1167672
    -/+ buffers/cache:    2217876    1761144
    Swap:      6029304     382832    5646472
  19. df: To show the discs and their status.
    Example: [root@testserver opt]# df
    Result:
    Filesystem           1K-blocks      Used Available Use% Mounted on
    /dev/mapper/VolGroup00-LogVol00
                         230601592   7762296 210936320   4% /
    /dev/sda1               101086     12508     83359  14% /boot
    tmpfs                  1989508         0   1989508   0% /dev/shm
  20. chmod -R MOD directory|file: To define permissions for specified directory or file. if you want to assign the permission to all containing files and sub-directory of the specified directory, you should use -R else it is not necessary. MOD is a 3 or 4 digits. every digits has it own meaning. Take a look the following gadget. click any box and see the result. the result will be the MOD.

    R W X
    Owner
    Group
    Others
    Result:
  21. export variableName="value": to define a variable with specified name and value.
    Example: [root@testserver opt]# export test="/opt/data"
    Result: test variable will be created.
  22. echo $variableName: to show variable value.
    Example: [root@testserver opt]# echo $test
    Result: /opt/data
I think it is enough for today. Maybe I will explain something around it in my future posts like: how to setup something, create a service, run something in start up and so on.


all rights reserved by Mostafa Rastgar and Programmer Assistant weblog

No comments: