Sunday, 15 November 2015

How to copy files remotely over ssh

SCP stands for secure cp (copy), It allows files to be copied to, from, or between different hosts. It uses ssh for data transfer and securely encrypted.

Syntax:
scp [[user@]host1:]file1 ... [[user@]host2:]file2

Examples:

  • Copy the file "foo.txt" from a remote host to the local host
    • $scp username@remotehost.com:foo.txt  /local/linuxinanutshell
  • Copy the file "foo.txt" from the local host to a remote host
    • $scp foo.txt username@remotehost.com:/remote/linuxinanutshell 
  • Copy multiple files using single command
    • $scp file1.txt file2.txt file3.txt username@remotehost.com:/remote/linuxinanutshell

To Increase Speed of scp command:
If you need more speed and still have security, you can use Blowfish or RC4.
scp -c blowfish username@remotehost.com:foo.txt  /local/linuxinanutshell

Or use RC4 which seems to be the fastest
scp -c arcfour username@remotehost.com:foo.txt  /local/linuxinanutshell .

This last one is not very secure, and it may not be used if security is really an issue for you.

You can also limit the bandwidth used by scp command:
Syntax:
scp -l limit username@server:/path/to/file /path/to/folder

Where limit is specified in Kbit/s. So for example, if you want to limit speed at 100 Kbps
Example:
scp -l100 username@remotehost.com:foo.txt  /local/linuxinanutshell 

Saturday, 14 November 2015

Set Time, Date Timezone in Linux from Command Line

Correct Date & Time in Operating System is very important and lot of things depends on it such as application compilation, etc. To view Date through command line:
$ date
Sat Nov 14 14:14:18 IST 2015

To set the year:
date -s 'next year'
date -s 'last year'

To set the month:
date -s 'last month'
date -s 'next month'

To set the day:
date -s 'next day'
date -s 'tomorrow'
date -s 'last day'
date -s 'yesterday'
date -s 'friday'

To set all together:
$ date -s '2015-11-15 14:21:30'
Sun Nov 15 14:21:30 IST 2015

To change part of the date, enter the date part that you want to change as a string and remains all others as date formatting variables. Refer below command which sets the 2016 year
$ date -s "$(date +'2016%m%d %H:%M')"
Mon Nov 14 14:25:00 IST 2016

The date formats are:

  • %Y - Year
  • %m - Month
  • %d - Day
  • %H - Hour
  • %M - Minute

Hardware time

Now the system time is set, but you may want to sync it with the hardware clock:

Use --show to print the hardware time:
hwclock --show

You can set the hardware clock to the current system time:
hwclock --systohc

Or the system time to the hardware clock:
hwclock --hctosys

To set the timezone

To set the timezone of your system clock do the following:
cp /usr/share/zoneinfo/Asia/Kolkata  /etc/localtime

Automatically adjust your system clock

To have your system to automatically adjust time we need to install ntp. Get it from your repository. Once installed you can configure it by editing configuration file /etc/ntpd.conf

Make sure to start the daemon, and to make it start automatically when the system boots.
/etc/init.d/ntpd start

To update from the command line against a time server:
ntpdate 10.22.10.4

Sunday, 1 November 2015

What is SELinux

SELinux
       SELinux (Security Enhanced Linux) is a Mandatory Access Control system built on Linux's LSM (Linux Security Modules) interface. In practice, the kernel queries SELinux before each system call to know whether the process is authorized to do the given operation.
       SELinux uses a set of rules — collectively known as a policy — to authorize or forbid operations. Those rules are difficult to create. Fortunately, two standard policies (targeted and strict) are provided to avoid the bulk of the configuration work.


Policies
       Policy - A set of declarations and rules, telling the SELinux core in the kernel what is permitted and how to behave in different situations

  • Targeted policy - A policy based upon the paradigm, that only a few selected applications should be restricted by SELinux. All other activity relies on good old UNIX security
  • Strict policy - A policy which attempts to control all activity with SELinux


Do I have SELinux?
       If you have a /selinux directory with something in it, SELinux is loaded in the kernel. Also try the sestatus command:
$ sestatus | grep -i mode
Current mode:                   enforcing
Mode from config file:          enforcing
Note: SELinux is enabled and in enforcing mode.


What SELinux is actually doing?
       SELinux is loaded in the kernel and performs three ongoing tasks, based upon the rules loaded from user space (i.e. the Policy):

  • Grant or deny access permission to processes requesting to perform action on objects
  • Grant or deny permission for context changes of objects and processes.
  • Decide what context to give to new objects and processes at their creation.

SELinux permissions are given on top of classic UNIX permissions. An action will take place only if both permissions are granted.

Enabling or Disabling Enforcement
       You can enable and disable SELinux enforcement at runtime or configure it to start in the correct mode at boot time, using the command line or GUI. SELinux can operate in one of three modes:

  • Disabled: meaning not enabled in the kernel.
  • Permissive: meaning SELinux is running and logging but not controlling permissions.
  • Enforcing: meaning SELinux is running and enforcing policy.

Use the setenforce command to change between permissive and enforcing modes at runtime. Use setenforce 0 to enter permissive mode; use setenforce 1 to enter enforcing mode.
$ setenforce 1

SELinux configurations from GUI
       You can configure all of these settings using system-config-selinux. The same configuration files are used, so changes appear bidirectionally. Use the following procedure to change a runtime boolean using the GUI.
Note: Administrator privileges are required to perform this procedure.

  • On the System menu, point to Administration and then click Security Level and Firewall to display the Security Level Configuration dialog box.
  • Click the SELinux tab, and then click Modify SELinux Policy.
  • In the selection list, click the arrow next to the Name Service entry, and select the Disable SELinux protection for named daemon check box.
  • Click OK to apply the change. Note that it may take a short time for the policy to be reloaded.


Saturday, 11 July 2015

How to sort contents of a file

sort command is used to sort the contents of a file. You can sort the data in text file and display the output on the screen, or redirect it to a file. Based on your requirement, sort provides several command line options for sorting data in a text file.

Syntax:
sort [options] filename

Examples:

#1 To sort text file [sort sort_file]

#2 To sort numbers in file, use -n option [sort -n sort_number_file]


#3 To sort months in file, use -M option [sort -M sort_month_file]

Refer below tables for more sort command options:
-b  Ignores leading spaces in each line 
 -d  Uses dictionary sort order. Conisders only spaces and alphanumeric characters in sorting 
 -f  Uses case insensitive sorting. 
 -M  Sorts based on months.  Either mention complete month name or only first 3 letters. Eg: JAN, FEB 
 -n  Uses numeric sorting 
 -R  Sorts the input file randomly. 
 -r  Reverse order sorting 
 -k  Sorts file based on the data in the specified field positions. 
 -u  Suppresses duplicate lines 
 -t  input field separator 





Wednesday, 1 July 2015

How to use sed command in Linux

sed, short for "stream editor", allows you to filter and transform text. A stream editor is used to perform basic text transformations on an input stream (a file, or input from a pipeline). While in some ways similar to an editor which permits scripted edits (such as ed), sed works by making only one pass over the input(s), and is consequently more efficient. But it is sed's ability to filter text in a pipeline which particularly distinguishes it from other types of editors.

How sed Works
sed maintains two data buffers: the active pattern space, and the auxiliary hold space. Both are initially empty.

sed operates by performing the following cycle on each line of input: first, sed reads one line from the input stream, removes any trailing newline, and places it in the pattern space. Then commands are executed; each command can have an address associated to it: addresses are a kind of condition code, and a command is only executed if the condition is verified before the command is to be executed.

When the end of the script is reached, unless the -n option is in use, the contents of pattern space are printed out to the output stream, adding back the trailing newline if it was removed. Then the next cycle starts for the next input line.

Syntax:
sed Options... [Script] [InputFile...]

Option
Detail
-n, --quiet, --silent Suppress automatic printing of pattern space.
-e script, --expression=script Add the script script to the commands to be executed.
-f script-file, --file=script-file Add the contents of script-file to the commands to be executed.
--follow-symlinks Follow symlinks when processing in place.
-i[SUFFIX], --in-place[=SUFFIX] Edit files in place (this makes a backup with file extension SUFFIX, ifSUFFIX is supplied).
-l N, --line-length=N Specify the desired line-wrap length, N, for the "l" command.
--POSIX Disable all GNU extensions.
-r, --regexp-extended Use extended regular expressions in the script.
-s, --separate Consider files as separate rather than as a single continuous long stream.
-u, --unbuffered Load minimal amounts of data from the input files and flush the outputbuffers more often.

Example:
#Replacing word in a file and save the output in same file.
       sed -i 's/blogger/blog/g' test_sed.txt

Sunday, 21 June 2015

How to create/remove directory/folder in Linux

mkdir command is used to create directory/folder on linux file system.

Syntax:
mkdir [OPTION] DIRECTORY

Refer below options used in mkdir command:

-m, --mode=MODE Set file mode (as with the chmod command).
-p, --parents Create parent directories as necessary. When this option is used, no error is reported if a specified DIRECTORY already exists.
-v, --verbose Verbose output; print a message for each created directory.
--help Display a help message, and exit.

Note: If directory already exists then command will modify the creation time of directory.

Examples:

#Creates a new directory called linuxinanutshell whose parent is the current directory.
mkdir linuxinanutshell

#Create the linuxinanutshell directory, and set its permissions such that all users may read, write, and execute the contents.
mkdir -m a=rwx linuxinanutshell

#Creates the directory /home/linuxinanutshell/a/b/c. If the parent directory /home/linuxinanutshell/a/b/c does not already exist, mkdir will create that directory first.
mkdir -p /home/linuxinanutshell/a/b/c


To remove directory, use rmdir command

The rmdir utility removes the directory entry specified by each directory argument, provided the directory is empty.


Arguments are processed in the order given. In order to remove both a parent directory and a subdirectory of that parent, the subdirectory must be specified first so the parent directory is empty when rmdir tries to remove it.

Syntax:
rmdir [-p] directory



--ignore-fail-on-non-empty ignore any failure which occurs solely because a directory is non-empty.
-p Each directory argument is treated as a pathname of which all components will be removed, if they are empty, starting with the lastmost component. (See rm for fully non-discriminant recursive removal.)
-v, --verbose Display verbose information for every directory processed.
--help Display a help message, and exit.

Example:
rmdir linuxinanutshell


Wednesday, 17 June 2015

How to Change permission of a file in linux

chmod command is used to change the permissions of files or directories. In Linux, there is a set of rules for each file which defines who can access that file, and how they can access it. These rules are called file permissions or file modes. The command name chmod stands for "change mode", and it is used to define the way a file can be accessed.

Syntax:
chmod [options] <permissions> <filename>

Note: If no options are specified, chmod modifies the permissions of the file specified by filename to the permissions specified by permissions.
Permissions defines the permissions for the owner of the file (the "user"), members of the group who owns the file (the "group"), and anyone else ("others"). There are two ways to represent these permissions: with symbols (alphanumeric characters), or with octal numbers (the digits 0 through 7).

Example[with symbols]: chmod u=rwx,g=rx,o=r test_file
chmod_symbolic_permissions

This is an example of using symbolic permissions notation. The letters u, g, and o stand for "user", "group", and "other". The equals sign ("=") means "set the permissions exactly like this," and the letters "r", "w", and "x" stand for "read", "write", and "execute", respectively.

Example[with octal numbers]: chmod 754 test_file

Here the digits 7, 5, and 4 each individually represent the permissions for the user, group, and others, in that order. Each digit is a combination of the numbers 4, 2, 1, and 0:
4 stands for "read",
2 stands for "write",
1 stands for "execute", and
0 stands for "no permission."
So 7 is the combination of permissions 4+2+1 (read, write, and execute), 5 is 4+0+1 (read, no write, and execute), and 4 is 4+0+0 (read, no write, and no execute).

Sunday, 14 June 2015

How to extract archive file in linux

tar command is used for extracting content from archive file. "tar" stands for tape archive, which is used to create, maintain, modify, and extract files that are archived in the tar format.

Syntax:
tar [options] [pathname]

Following options are widely used with tar utility

A, --catenate, --concatenate Append tar files to an archive.
c, --create Create a new archive.
d, --diff, --compare Calculate any differences between the archive and the file system.
-v, --verbose Operate verbosely.
t, --list List the contents of an archive.
x, --extract, --get Extract files from an archive.


Refer below tar examples:

#Create a new tar archive.
$ tar cvf linux_archive.tar dirname/

Note: In above example, c means create a new archive, v means verbosely list files which are processed and f means following is the archive file name

#Extract from an existing tar archive.
$ tar xvf linux_archive.tar

#View an existing tar archive.
$ tar tvf linux_archive.tar

#To estimate the tar file size ( in KB ) before you create the tar file.
$ tar -cf - /directory/to/archive/ | wc -c
O/P: 20480

How to use crontab in linux

cron is the system process which will automatically perform tasks for you according to a set schedule. The schedule is called the crontab, which is also the name of the program used to edit that schedule.

crontab is the program used to edit, remove or list the tables used to drive the cron daemon. cron jobs can be allowed or disallowed for individual users, as specified in the files cron.allow and cron.deny, located in the directory /etc. If the cron.allow file exists, a user must be listed there in order to be allowed to use a given command. If the cron.allow file does not exist but the cron.deny file does, then a user must not be listed there in order to use a given command. If neither of these files exists, only the superuser will be allowed to use a given command.

Syntax:
crontab [-u user] [-l | -r | -e] [-i] [-s]

Example:
Let's say you have a script which backs up important files, or creates a report about system statistics, for example. Let's say the script is called /tmp/linuxinanutshell/scripts/do-every-day.sh, and you want to run it every morning at 5 A.M.

To edit the crontab, use this command:
crontab -e

This will open the crontab in a text editor (Usually this is vi or vim, but it may be something else depending on your Linux distribution). Save below entry in opened file:

0 5 * * * /tmp/linuxinanutshell/scripts/do-every-day.sh

Cron Command Format

Each cron command in the crontab file has five time and date fields, followed by a user name if it is the system crontab file, followed by a command. Commands are executed by cron when the minute, hour, and month of year fields match the current time, and at least one of the two day fields (day of month, or day of week) match the current time.

Field Allowed values
minute 0-59
hour 0-23
day of month 1-31
month 1-12 (or names)
day of week 0-7 (0 or 7 is Sun, or use names)

Refer other examples:

#This example checks the status of the database everyday (including weekends) during the working hours 9 a.m – 6 p.m
00 09-18 * * * /tmp/linuxinanutshell/scripts/db-status

#This example will check the disk space every 10 minutes.
*/10 * * * * /tmp/linuxinanutshell/scripts/disk-check.sh

#This example will execute the shell script tape-backup at 00:00 on 1st of every month.
@monthly /tmp/linuxinanutshell/scripts/backup.sh

Friday, 3 April 2015

Use of man/whatis/apropos commands

The man command is used to format and display the man pages. The man pages are a user manual that is by default built into most Linux distributions It provide extensive documentation about commands and other aspects of the system, including configuration files, system calls, library routines and the kernel (i.e., the core of the operating system)

Syntax:
man [options] keyword/name

man is most commonly used without any options and with only one keyword. The keyword is the exact name of the command or other item for which information is desired. For example, the following provides information about the ls command (which is used to list the contents of any specified directory):

$ man ls

Following are different options can be used with man command:
C config_file  Specify the configuration file to use; the default is /etc/man.config. 
M path Specify the list of directories to search for man pages. Separate the directories
with colons. An empty list is the same as not specifying -M at all. 
a By default, man will exit after displaying the first manual page it finds. Using this
option forces man to display all the manual pages that match name, not just the
first.
c Reformat the source man page, even when an up-to-date cat page exists. This
can be meaningful if the cat page was formatted for a screen with a different
number of columns, or if the preformatted page is corrupted.
d Don't actually display the man pages, but do print gobs of debugging information.
D Both display and print debugging info.
f Equivalent to whatis.
F or --preformat Format only - do not display.
h Print a one-line help message and exit.
k Equivalent to apropos.
K Search for the specified string in *all* man pages. Warning: this is probably very
slow! It helps to specify a section. 

The Whatis and Apropos Commands
       During your Linux exploration, it sometimes happens that you forget a command or two or misremember what it does. Luckily, Linux takes this into consideration and has a solution to help retrieve those commands that have escaped into the forgettery.

Whatis Command
       Whatis is a command that's bound to come in handy, especially while you're learning Linux. By typing "whatis" followed by a command, Linux returns the first line of the Man-page (manual page) for that command. Here's an example to show you what the "cp" command does:

$ whatis cp
This returns:
cp (1) - copy files and directories
The command is listed followed by a number in parentheses. The number refers to the section of the man-pages (manual pages) that the command can be found in.

For the command ifconfig:
$ whatis ifconfig
ifconfig (8) - configure a network interface
If you wanted more information about one of the commands, then you need to use man command.

Apropos Command
       Linux knows so many commands, it's impossible to remember them all. Imagine you know only a part of the name or description of a command. Say for example, you remember "zip," but not the complete command.
       You can use the apropos command to find Linux commands that are related to one or more keywords. As i mentioned, if you remember only "zip" word then you can type:
 $ apropos zip
which will write out a table containing all Linux commands that include "zip" in the command name or in the brief description provided in the Name section of the man page of the command.


Sunday, 29 March 2015

Linux File System

       In the Linux file structure files are grouped according to purpose. Ex: commands, data files, documentation. Several major directories are associated with all modern Unix/Linux operating systems. These directories organize user files, drivers, kernels, logs, programs, utilities, and more into different categories. The standardization of the FHS [Filesystem Hierarchy Standard] makes it easier for users of other Unix-based operating systems to understand the basics of Linux.

       Every FHS starts with the root directory, also known by its label, the single forward slash (/). All of the other directories shown in Table are subdirectories of the root directory. Unless they are mounted separately, you can also find their files on the same partition as the root directory.

root(/)  The home directory for the root user
/home Contains the user's home directories along with directories for services
ftp
HTTP
samba 
/bin Commands needed during bootup that might be needed by normal users
/sbin Like bin but commands are not intended for normal users. Commands run by LINUX.
/proc This filesystem is not on a disk. It is a virtual filesystem that exists in the kernels
imagination which is memory.  A directory with info about process number  and each process has a directory under proc.
/usr Contains all commands, libraries, man pages, games and static files for normal operation.
bin
Almost all user commands. some commands are in /bin or /usr/local/bin.
sbin
System admin commands not needed on the root filesystem. e.g., most server programs.
include
Header files for the C programming language. Should be below /user/lib for consistency.
lib
Unchanging data files for programs and subsystems
local
The place for locally installed software and other files.
man
For manual pages
info 
For Info documents
doc
For Documentation
/boot Files used by the bootstrap loader, LILO. Kernel images are often kept here.
/lib Shared libraries needed by the programs on the root filesystem
modules
Loadable kernel modules, especially those needed to boot the system after
disasters.
/dev Stored Device files
/etc Configuration files specific to the machine.
skel
When a home directory is created it is initialized with files from this directory
sysconfig
Files that configure the linux system for devices.
/var Contains files that change for mail, news, printers log files, man pages, temp files
lib
Files that change while the system is running normally
local
Variable data for programs installed in /usr/local.
lock
Lock files. Used by a program to indicate it is using a particular device or file
log
Log files from programs such as login and syslog which logs all logins and
logouts.
run
Files that contain information about the system that is valid until the system is
 next booted
spool
Directories for mail, printer spools, news and other spooled work.
tmp
Temporary files that are large or need to exist for longer than they should in /tmp.
catman
A cache for man pages that are formatted on demand
/mnt Mount points for temporary mounts by the system administrator.
/tmp Temporary files. Programs running after bootup should use /var/tmp.

Types of Files Used by Linux
       When working with Linux, you need to be aware of the fact that there are a number of different file types used by the file system. This is another area where the Linux file system differs significantly from the Windows file system. In Linux, there are a variety of different file types used by the file system. These include the file types shown in Table:
File Type Description
Regular files
These files are similar to those used by the file systems of other operating systems—for example, executable files, OpenOffice.org files, images, text configuration files, etc.
Links
These files are pointers that point to other files in the file system.
FIFOs
FIFO stands for First In First Out. These are special files used to move data from one running process on the system to another. A FIFO file is basically a queue where the first chunk of data added to the queue is the first chunk of data removed from the queue. Data can only move in one direction through a FIFO.
Sockets
Sockets are similar to FIFOs in that they are used to transfer information between sockets. With a socket, however, data can move bidirectionally.

The File system in reality
       For most users and for most common system administration tasks, it is enough to accept that files and directories are ordered in a tree-like structure. The computer, however, doesn't understand a thing about trees or tree-structures.
       Every partition has its own file system. By imagining all those file systems together, we can form an idea of the tree-structure of the entire system, but it is not as simple as that. In a file system, a file is represented by an inode, a kind of serial number containing information about the actual data that makes up the file: to whom this file belongs, and where is it located on the hard disk.
       Every partition has its own set of inodes; throughout a system with multiple partitions, files with the same inode number can exist.
       Each inode describes a data structure on the hard disk, storing the properties of a file, including the physical location of the file data. When a hard disk is initialized to accept data storage, usually during the initial system installation process or when adding extra disks to an existing system, a fixed number of inodes per partition is created. This number will be the maximum amount of files, of all types (including directories, special files, links etc.) that can exist at the same time on the partition. We typically count on having 1 inode per 2 to 8 kilobytes of storage.

At the time a new file is created, it gets a free inode. In that inode is the following information:

  • Owner and group owner of the file.
  • File type (regular, directory, ...)
  • Permissions on the file
  • Date and time of creation, last read and change.
  • Date and time this information has been changed in the inode.
  • Number of links to this file (see later in this chapter).
  • File size
  • An address defining the actual location of the file data.

       The only information not included in an inode, is the file name and directory. These are stored in the special directory files. By comparing file names and inode numbers, the system can make up a tree-structure that the user understands. Users can display inode numbers using the -i option to ls. The inodes have their own separate space on the disk.
$ ls -il
total 1
 639036 -rw-r--r--    1 Anil     Administ       24 Mar  1 20:12 file1.txt
2044316 -rw-r--r--    1 Anil     Administ       24 Mar  1 21:26 file2.txt
You can see the inode number of files [file1.txt & file2.txt] highlighted in Red.

Tuesday, 24 March 2015

How to delete user in Linux

To delete user, you can use userdel command. Refer below syntax:
$ userdel [options] <username>

Example:
$ userdel anil

To remove the user's home directory pass the -r option to userdel:
$ userdel -r anil

Default values of userdel command are taken from configuration file /etc/login.defs  for RHEL (Red Hat) based distributions. Debian and Ubuntu Linux based system use /etc/deluser.conf file:

 # /etc/deluser.conf: deluser configuration - Debian / Ubuntu Linux only.

# Remove home directory and mail spool when user is removed
REMOVE_HOME = 0

# Remove all files on the system owned by the user to be removed
REMOVE_ALL_FILES = 0

# Backup files before removing them. This options has only an effect if
# REMOVE_HOME or REMOVE_ALL_FILES is set.
BACKUP = 0

# target directory for the backup file
BACKUP_TO = "."

# delete a group even there are still users in this group
ONLY_IF_EMPTY = 0

# exclude these filesystem types when searching for files of a user to backup
EXCLUDE_FSTYPES = "(proc|sysfs|usbfs|devpts|tmpfs)"

Sunday, 22 March 2015

How to add user in linux

To add user, you can use useradd command in linux. Refer below syntax:

useradd [options] <user-name>

Example: useradd anil

While creating users as mentioned above, all the default options will be taken except group id. To view the default options give the following command with the option -D.

$ useradd -D
GROUP=1001
HOME=/home
INACTIVE=-1
EXPIRE=
SHELL=/bin/sh
SKEL=/etc/skel
CREATE_MAIL_SPOOL=no
GROUPThis is the only option which will not be taken as default. Because if you don’t specify -n option a group with same name as the user will be created and the user will be added to that group. To avoid that and to make the user as the member of the default group you need to give the option -n.
HOMEThis is the default path prefix for the home directory. Now the home directory will be created as /home/USERNAME.
INACTIVE-1 by default disables the feature of disabling the account once the user password has expired. To change this behavior you need to give a positive number which means if the password gets expired after the given number of days the user account will be disabled.
EXPIREThe date on which the user account will be disabled.
SHELLUsers login shell.
SKELContents of the skel directory will be copied to the users home directory.
CREATE_MAIL_SPOOLAccording to the value creates or does not create the mail spool.

To create user with custom configurations using useradd Command:
The below example creates an account "anil" with home directory /home/linuxbasics, default shell as /bin/ksh and with comment “Linuxinanutshell admin”.

$ useradd -s /bin/ksh -m -d /home/linuxbasics -c “Linuxinanutshell admin” -g root anil

$ grep anil /etc/passwd
anil:x:1083:0:Linuxinanutshell admin:/home/linuxbasics:/bin/ksh

To change default options in configuration file:
As we mentioned earlier to change the default values during command execution, there is another option to change default values for account creation, which is defined in /etc/default/useradd file under most of the Linux distributions. Open this file in a text editor, ie.:
$ vi /etc/default/useradd

The default home directory defined by HOME variable, find line that read as follows:
HOME=/home

Replace with:
HOME=/linuxbasics/user

Save and close the file. Now you can add user using regular useradd command:
$ useradd anil


To change existing User's Home Directory:
You need to use the usermod command to set the user's new login directory.

Syntax: usermod -m -d /path-to-new-home-dir userName

-d dirnanme : Path to new login (home) directory.
-m : The contents of the current home directory will be moved to the new home directory, which is created if it does not already exist.

Example: usermod -m -d /users/linuxinanutshell/anil anil
In above example set the user's new login directory to /users/linuxinanutshell/anil from /home/anil

To set Password for user:
$ passwd anil
Changing password for user anil.
New UNIX password:
Retype new UNIX password:
passwd: all authentication tokens updated successfully.

[Note: Always set the password immediately after user creation]

Saturday, 7 March 2015

Kill or terminate process in Linux

Kill command is used to kill a process in Linux.The kill command sends the specified signal such as kill process to the specified process. If no signal is specified, the SIGTERM signal is sent.

Syntax:

kill [signal] PID

A list of common signals:
SIGHUP-(1) Hangup detected on controlling terminal or death of controlling process. Use SIGHUP to reload configuration files and open/close log files
SIGKILL-(9) Kill signal. Use SIGKILL as a last resort to kill process. This will not save data or cleaning kill the process
SIGTERM-(15) Termination signal. This is the default and safest way to kill process

Example:
In example, we are terminating process java with -15 signal, which will terminate the process safely.

Points to remember:

  • You can kill all your own process.
  • Only root user can kill system level processes.
  • Only root user can kill process started by other users.

To kill multiple process in single command, mention all PID's in command:
kill -15 PID1 PID2 PID3


To kill process with its name:
You can kill any process by specifying its full name or partial name. So there is no need for you to find out the PID of the process to send the signal.
pkill java
Further, you can also kill process with its name using killall command but with killall, you need to specify full name of process.


Note: There are many kill signals that each serve a particular purpose. Typing "kill -l" will list the kill signals. 



Sunday, 1 March 2015

Find difference between 02 files in linux

To compare two text files in Linux, use the diff command. In nutshell, diff compares the contents of the two files from-file and to-file.
Syntax: diff [options] from-file to-file2
Following options can be used with diff command:
-b Ignore changes in amount of white space.
-B Ignore changes that just insert or delete blank lines.
-i Ignore changes in case; consider upper- and lower-case letters equivalent.
--new-file In directory comparison, if a file is found in only one directory, treat it as present but empty in the other directory.
-r When comparing directories, recursively compare any subdirectories found.
Example:
Suppose you have a file 'file1.txt': 
and another file 'file2.txt':
Now, if you execute the diff command 'diff file1.txt file2.txt', then it will display the output like this:
Lines "1d0" and "6a6" are the coordinates and types of the differences between the two compared files, while lines like "< aa" and "> kk" are the differences themselves. Diff change notation includes 2 numbers and a character between them. Characters tell you what kind of change was discovered:

a – line added

c – line changed

d – line deleted

Left number of the character defines the line number in the first file, and Right number of the character defines the line number in the second file.
Output details:
1d0
< aa
It means that 1 line was deleted. < aa denotes that the aa line is present only in the first file.
3c2
< cc
---
> kk
It means that the line#3 has changed from "cc"[in first file] to "kk"[in second file].
6a6
> gg
It means that one new line added in the second file, it's "gg" at line#7.


Friday, 20 February 2015

how to get file/directory stat or information

The stat command is used to display detailed status of file, directory and file system.
Syntax: stat [options] FILE...

Example:
$ stat tmp/file1
Output:
File: tmp/file1
Size: 0 Blocks: 0  IO Block: 4096
Device: 12h/18d Inode: 3064192624  Links: 1
Access: (0660/-rw-rw----)  Uid: (    0/ UNKNOWN)   Gid: ( 1028/ UNKNOWN)
Access: 2015-02-28 15:39:03.000000000
Modify: 2015-02-28 15:39:03.000000000
Change: 2015-02-28 15:39:03.000000000

So, without options/arguments you can have the following details:

File
Size in Bytes
Blocks
Number of blocks used
IO Block
Size in bytes of every block
Device
The identifier number of your storage device (harddrive, etc.)
Inode
The inode number that the file or directory is linked to
Access/Modify and change Times
Note that the timestamps also include which time zone that accesses or modifications took place in

Arguments:
The following are some of the flags and arguments that can be used for the stat command:


Arguments
Details
-f  --filesystem
display filesystem status instead of file status
-c   --format
use the specified FORMAT instead of the default
-L  --dereference
follow links
-Z   --context
print the security context
--help
display the help and exit

Sunday, 1 February 2015

How to use find command in linux

Intro
Find utility searches for files in a directory. Basically files can be found under Linux in many different ways. Using the find utility is one of the best ways to find files. The find utility has a huge number of parameters which can be set so that Linux finds exactly those files that you were searching for.

Syntax
find  where_to_look  criteria  which_file_want_to_search

Example
$ find / -name report 2>/dev/null

/ Start searching from the root directory
-name Given search text is the filename rather than any other attribute of a file
report File name for which we are looking

Note
2> /dev/null is not related to find utility. Here, 2 indicates the error stream in Linux, and /dev/null is the device where anything you send simply disappears i.e. Above example discard all error messages.

Friday, 16 January 2015

Search pattern using grep command in Linux

You can search word in file using grep command.

Syntax:
grep [options] <pattern> <file(s)>

Examples with different options:
1. grep anil file1
2. To search exact word in file
      grep -w 'anil' file2
3. To search words in multiple files or in directory
      grep -r 'anil' /tmp
4. Case insensitive search
      grep -i "Anil' file3


Note: If you want to discard errors during above commands execution, then redirect errors in /dev/null using below command [/dev/null is the device where anything you send simply disappears].

$ grep -w 'anil' /tmp/ 2> /dev/null

Thursday, 15 January 2015

create an empty file in linux

You can create an empty file using touch commad

Syntax:
touch [options] <filename or path to file>

Examples:
1. touch file1
2. Touch can also create any number of files simultaneously. The following command would create three new, empty files named file1, file2 and file3:
     touch file1 file2 file3
3. touch -t 201212101830.55 file1

Here’s the options for the command:
touch command options

Sunday, 11 January 2015

Copy/Move file in linux

You can copy/move file in linux using cp/mv command.

To copy file:
Syntax:
  • cp [options] <source file> <destination file>
  • cp [options] <source path of file> <destination path of file>
Examples:
  • cp file1 file2
  • cp /tmp/file1 /data/file2


To move file:
Syntax:
  • mv [options] <source file> <destination file>
  • mv [options] <source path of file> <destination path of file>
Examples:
  • mv file1 file2
  • mv /tmp/file1 /data/file2


Note: You can also use mv command to rename file