Category Archives: Linux Commands

Step by Step procedure to install and Configure ANSIBLE on Ubuntu

Step by step procedure to install and configure ansible on ubuntu

Before installing ANSIBLE, let us understand,

What is ANSIBLE ?

1.Ansible Introduction :

Ansible is an IT automation tool. It can configure systems, deploy software, and orchestrate more advanced IT tasks such as continuous deployments or zero
downtime rolling updates.
Ansible’s goals are foremost those of simplicity and maximum ease of use. It also has a strong focus on security and reliability, featuring a minimum of moving parts, usage of OpenSSH for transport (with an accelerated socket mode and pull modes as alternatives),
and a language that is designed around auditability by humans – even those not familiar with the program.

While there are many popular configuration management systems available for Linux systems, such as Chef and Puppet, these are often more complex than many people want or need.Ansible is a great alternative to these options because it has a much smaller overhead to get started.

for more information visit, Ansible docs.
http://docs.ansible.com/

Assumptions
● You have a ubuntu 12.04 and you are logged-in as root.

2.How Does Ansible Work :
Ansible works by configuring client machines from an computer with Ansible components
installed and configured.
It communicates over normal SSH channels in order to retrieve information from remote
machines, issue commands, and copy files. Because of this, an Ansible system does not require any additional software to be installed on the client computers.
This is one way that Ansible simplifies the administration of servers.
Configuration files are mainly written in the YAML data  format due to its
expressive nature and its similarity to popular markup languages.Ansible can interact with clients through either command line tools or through its configuration scripts called Playbooks.

3. Install Ansible on an Ubuntu 12.04 :
To begin exploring Ansible , we need to install the Ansible package on at least one machine. I have used ubuntu 12.04

git clone git@github.com:ansible/ansible.git
cd ansible
source ./hacking/env-setup
sudo pip install paramiko PyYAML jinja2 --upgrade

We now have all of the software required to administer our servers through Ansible.
Set Up SSH Keys , Ansible primarily communicates with client computers through SSH.While it certainly has the ability to handle password-based SSH authentication, SSH keys help keep things simple.

4. Creating a SSH Pair :
@Server:~> ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/a/.ssh/id_rsa):
Created directory ‘/home/a/.ssh’.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/a/.ssh/id_rsa.
Your public key has been saved in /home/a/.ssh/id_rsa.pub.
The key fingerprint is:
3e:4f:05:79:3a:9f:96:7c:3b:ad:e9:58:37:bc:37:e4 a@A
Now use ssh to create a directory ~/.ssh as user b on Client. (The directory may already exist,
which is fine):
@Server:~> ssh root@123.123.123.123 mkdir -p .ssh
root@Client’s password:
Finally append a’s new public key to root@123.123.123.123:.ssh/authorized_keys and enter
client’s password one last time:
root@Server:~> cat .ssh/id_rsa.pub | ssh root@123.123.123.123 ‘cat >> .ssh/authorized_keys’
root@Client’s password:
From now on you can log into Client as root from A as a without password:
@Server:~> ssh root@123.123.123.123

5. Configuring Ansible Host:
Ansible keeps record of all of the servers that it know through a “hosts” file. We need to configure this file first before we can begin to communicate with our other computers.
Open the file and add,

vim /etc/ansible/hosts
[hosts]
devops ansible_ssh_host=123.123.123.123

Where hosts is list of nodes
devops = host name of one of the client.
123.123.123.123 is hosts ip.
To do this, we will create a directory in the Ansible configuration structure called group_vars.
Within this folder, we can create YAML-formatted files for each group we want to configure:

sudo mkdir /etc/ansible/group_vars
sudo nano /etc/ansible/group_vars/hosts

We can put our configuration in here. YAML files start with “—“, so make sure you don’t forget that part.

ansible_ssh_user: root
Save and close this file when you are finished.

6. Ansible test Examples:

Using Simple Ansible Commands
Now that we have our hosts set up and enough configuration details to allow us to
successfully connect to our hosts, we can try out our very first command.
Ping all of the servers you configured by typing:
root@server:/etc/ansible# ansible -m ping hosts
devops | success >> {
“changed”: false,
“ping”: “pong”
}
This is a basic test to make sure that Ansible has a connection to all of its hosts.

ansible -m shell -a ‘ifconfig’ devops

devops | success | rc=0 >>
eth0 Link encap:Ethernet HWaddr 00:0c:29:a2:42:c4
inet addr:123.123.123.123 Bcast:10.27.111.255 Mask:255.255.255.0

ansible -m shell -a ‘free -m’ devops
devops | success | rc=0 >>
total used free shared buffers cached
Mem: 487 440 47 0 108 173
-/+ buffers/cache: 158 329
Swap: 507 66 441

Lets install sendmail on client from Ansible server, to do that create playbook.yml file in
/etc/ansible 100 Jul 5 02:48 playbook.yml

root@server:/etc/ansible# cat playbook.yml

– hosts: devops
tasks:
– name: 1. install sendmail
apt: name=sendmail state=present

Now execute below command to install on remote server.
ansible-playbook –inventory-file=hosts playbook.yml –sudo –verbose
Below is the result,

ansible 1

Before executing above command, sendmail was not installed. ansible 2

Later after execution, sendmail installed on the remote host.

Advantages of Automation,

,Automation-Advantages

Hence we have Installed and Configured ANSIBLE, Enjoy !!!

shell script to replace a string in a file

shell script to replace a string in a file

Some times during automating any task, we may require to replace a string in a file.
Example:- I want to change “Linux” string with “Waseem” in a file called string.txt

cat replacestring.sh
#!/bin/bash
# Shell Script to replace string in a file
/bin/sed -i “s/Linux/Waseem/g” /PATH/TO/FILE/string.txt
exit 0;

Before:-
—————–
cat string.txt
Linux

Run the script:-
——————-
sh replacestring.sh

After:-
——————
cat string.txt
Waseem

Another way we can replace string by passing parameter,so that the script will be used dynamically.
cat replacestring.sh
#!/bin/bash
# Shell Script to replace string in a file
/bin/sed -i “s/$1/$2/g” /PATH/TO/FILE/string.txt
exit 0;

Run the script:-
—————–
sh replacestring.sh Linux Waseem

Shell Script : Auto Enable/Disable Specific Cronjob

Shell Script : Auto Enable/Disable Specific Cronjob

What is Cronjob ?
A cron job is a scheduled task that is executed by the system at a specified time/date.

Sometimes we want to perform some task during specific time(Ex: During production Hours), and once the production time completes, we will be disabling cronjob. this requires manual work.The above manual work, can be automated with this script.

Create two scripts,
1.Auto_enable_cron.sh
2. Auto_disable_cron.sh

Below are both the scripts with cronjob details,

COMMANDS used:

crontab -l | sed ‘/^#.*GIVE-SCRIPT-NAME-HERE.sh/s/^#//’ | crontab –
crontab -l | sed ‘/^[^#].*GIVE-SCRIPT-NAME-HERE.sh/s/^/#/’ | crontab –

cronandscript

cronoutput

In the above image we can see that after running Auto_enable_cron.sh
The script in the cron GIVE-SCRIPT-NAME-HERE.sh is uncommented and after running
Auto-disable_cron.sh the script GIVE-SCRIPT-NAME-HERE.sh is commented again.

Now add scripts to desired time in cronjob.
9 * * * * /home/cronjob/Auto_enable_cron.sh (This will enable GIVE-SCRIPT-NAME-HERE.sh @9)
23 * * * * /home/cronjob/Auto_disable_cron.sh (This will disable GIVE-SCRIPT-NAME-HERE.sh @23)

Enjoy, just now you have automated your task!!!!.

Shell Script : Basic mathematics

#!/bin/bash
# SCRIPT: calc.sh
# PURPOSE: Addition, Subtraction, Division and Multiplication of
# two numbers.
#
#####################################################################
# Variable Declaration #
#####################################################################

clear #Clears Screen

Bold=”\033[1m” #Storing escape sequences in a variable.
Normal=”\033[0m”

echo “$Bold Basic mathematics using bash script $Normal\n”

items=”1. ADDITTION
2. SUBTRACTION
3. MULTIPLICATION
4. DIVISION
5. EXIT”

choice=

#####################################################################
# Functions Starts from here #
#####################################################################
exit_function()
{
clear
exit
}

#Function enter is used to go back to menu and clears screen

enter()
{
unset num1 num2
ans=
echo “”
echo -e “Do you want to continue(y/n):\c”
stty -icanon min 0 time 0
while [ -z “$ans” ]
do
read ans
done

#The while loop ensures that so long as at least one character is

if [ “$ans” = “y” -o “$ans” = “Y” ]
then
stty sane # Restoring terminal settings
clear
else
stty sane
exit_function
fi
}

#####################################################################
# CALC Script MENU #
#####################################################################

while true
do
echo “$Bold \tWelcome to Waseem’s Tutorial $Normal\n”
echo “\t$items \n”
echo -n “Enter your choice : ”
read choice

case $choice in
1) clear
echo “Enter two numbers for Addition : ”
echo -n “Number1: ”
read num1
echo -n “Number2: ”
read num2
echo “$num1 + $num2 = `expr $num1 + $num2`”
;;
2) clear
echo “Enter two numbers for Subtraction : ”
echo -n “Number1: ”
read num1
echo -n “Number2: ”
read num2
echo “$num1 – $num2 = $((num1-num2))”
enter ;;
3) clear
echo “Enter two numbers for Multiplication : ”
echo -n “Number1: ”
read num1
echo -n “Number2: ”
read num2
echo “$num1 * $num2 = `echo “$num1*$num2″|bc`”
enter ;;
4) clear
echo “Enter two numbers for Division : ”
echo -n “Number1: ”
read num1
echo -n “Number2: ”
read num2
let div=num1/num2
echo “$num1 / $num2 = $div”
enter ;;
5) exit_function ;;
*) echo “You entered wrong option, Please enter 1,2,3,4 or 5″
echo “Press enter to continue”
read
clear
esac

done

Output:-

Capture

shell scripting in linux

What is Linux ?
Linux is an open-source operating system modelled on UNIX.

What is Shell Script ?

A shell script is a computer program designed to be run by the Unix shell, a command line interpreter. The various dialects of shell scripts are considered to be scripting languages. Typical operations performed by shell scripts include file manipulation, program execution, and printing text.

Different types of shell in linux ?
Bourne shell (sh)
C shell (csh)
TC shell (tcsh)
Korn shell (ksh)
Bourne Again SHell (bash)

I like Bourne shell(sh), you will find many of my scripts in sh.

Bourne shell (sh):
—————————————————————————————
This is the original Unix shell written by Steve Bourne of Bell Labs. It is available on all UNIX systems.The Bourne shell does provide an easy to use language with which you can write shell scripts.

Purpose of Shell script ?
Many a times we do repetitive work, for example.
1. Taking Database dumps
2. Generating Reports
3. Configuration Backup’s etc..

The above tasks can be automated with the help of scripting.

Writing your first script and getting it work!!

————————————————————————————————

To successfully write a shell script, you have to do three things:

1. Write a script
2. Give the shell permission to execute it
3. Put it somewhere the shell can find it

Writing Script :-
——————————————————————————————
A shell script is a file that contains ASCII text. To create a shell script, we can use a text editor.
A text editor is a program, like a word processor, that reads and writes ASCII text files.
There are many text editors available for your Linux system, both for the command line environment and the GUI environment.
Here is a list of some common ones:
vi
vim
nano
gedit etc.

Writing your first script
————————–
vim myfirstscript.sh
#!/bin/bash
#My First Script to print text
#Author : xyz
#Developed Date : dd/mm/yyyy
echo “Hello, This is my first script”
——————————————–
save and exit.

Give executable permissions,
chmod 755 myfirstscript.sh

we can run the script in two ways,
1. sh myfirstscript.sh
2. ./myfirstscript.sh

After running script, you should see “Hello, This is my first script” . you have just wrote a simple shell script and it worked!!

Perform SCP Without Entering Password

In this article, I’ll explain how to perform scp without entering the password using the SSH Public Key authentication. There will be requirements like you would like to transfer files from one server to another with scripts and run it as cronjob. There are two levels of security in the SSH key based authentication. In order for you to login, you need both the private key and the passphrase. Even if one of them is compromised, attacker still cannot login to your account, as both of them are needed to login. This is far better than typical password based authentication, where if the password is compromised, attacker can gain access to the system.

There are two ways to perform ssh and scp without entering the password:

  1. No passphrase. While creating key pair, leave the passphrase empty. Use this option for the automated batch processing. for e.g. if you are running a cron job to copy files between machines this is suitable option.
  2. Use passphrase and SSH Agent. If you are using ssh and scp interactively from the command-line and you don’t want to use the password everytime you perform ssh or scp, I don’t recommend the previous option (no passphrase), as you’ve eliminated one level of security in the ssh key based authentication. Instead, use the passphrase while creating the key pair and use SSH Agent to perform ssh and scp without having to enter the password everytime as explained in the steps below.

Step:1. Verify that local-host and remote-host is running openSSH

[local-host]$ ssh -V
OpenSSH_4.3p2, OpenSSL 0.9.8b 04 May 2006

[remote-host]$ ssh -V
OpenSSH_4.3p2, OpenSSL 0.9.8b 04 May 2006

Step:2. Generate key-pair on the local-host using ssh-keygen

[local-host]$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/waseem/.ssh/id_rsa):<Hit enter>
Enter passphrase (empty for no passphrase): <Enter your passphrase here>
Enter same passphrase again:<Enter your passphrase again>
Your identification has been saved in /home/waseem/.ssh/id_rsa.
Your public key has been saved in /home/waseem/.ssh/id_rsa.pub.
The key fingerprint is:

The public key and private key are typically stored in .ssh folder under your home directory. In this example, it is under /home/waseem/.sshd. You should not share the private key with anybody.

Step:3. Install public key on the remote-host.

Copy the content of the public key from the local-host and paste it to the /home/waseem/.ssh/authorized_keys on the remote-host. If the /home/waseem/.ssh/authorized_keys already has some other public key, you can append this to the end of it. If the .ssh directory under your home directory on remote-host doesn’t exist, please create it.
[remote-host]$ vi ~/.ssh/authorized_keys 

In simple words, copy the local-host:/home/waseem/.ssh/id_rsa.pub to remote-host:/home/jsmith/.ssh/authorized_keys

Step:4. Give appropriate permission to the .ssh directory on the remote-host.

[remote-host]$ chmod 755 ~/.ssh
[remote-host]$ chmod 644 ~/.ssh/authorized_keys

Step:5. Login from the local-host to remote-host using the SSH key

[local-host]$ <You are on local-host here>

[local-host]$ ssh -l waseem remote-host
Last login: Sat Jun 07 2008 23:03:04 -0700 [remote-host]$ <You are on remote-host here>

Step:6 Verify SCP working without password from local server

scp testscpwithoutpassword.csv  waseem@192.168.1.1:/home/waseem

CHAPTER 5 : ESSENTIAL LINUX COMMANDS : TAR

Syntax:

tar [options] [tar-archive-name] [other-file-names]

How can I create a single backup file of all files and
subdirectories under my home directory?
The following command creates a single archive backup file called
my_home_directory.tar under /tmp. This archive will contain all the files and subdirectories under /home/jsmith.

• Option c, stands for create an archive.
• Option v stands for verbose mode, displays additional
information while executing the command.
• Option f indicates the archive file name mentioned in the

command.

# tar cvf /tmp/my_home_directory.tar /home/jsmith

How do I view all the files inside the tar archive?
Option t will display all the files from the tar archive.# tar tvf /tmp/my_home_directory.tar

How do I extract all the files from a tar archive?
Option x will extract the files from the tar archive as shown below. This
will extract the content to the current directory location from where the
command is executed.
# tar xvf /tmp/my_home_directory.tar

How do I extract tar.gz files to a specific directory?
# tar xvfz /tmp/my_home_directory.tar.gz –C /home/ramesh

How to use gzip with tar?
Add option z to the tar command when dealing with tar.gz compressed
file.
# tar cvfz /tmp/my_home_directory.tar.gz /home/jsmith
# tar xvfz /tmp/my_home_directory.tar.gz
# tar tvfz /tmp/my_home_directory.tar.gz

Note: Using gzip is faster when compared to bzip2.

How to use bzip2 with tar?
Add option j to the tar command when dealing with tar.bz2 compressed
file.
# tar cvfj /tmp/my_home_directory.tar.bz2 /home/jsmith
# tar xvfj /tmp/my_home_directory.tar.bz2
# tar tvfj /tmp/my_home_directory.tar.bz2

Note: Using bizp2 gives higher level of compression when compared to gzip.

CHAPTER 4 : ESSENTIAL LINUX COMMANDS : DATE

Set System Date and Time

To change the system date use:
# date {mmddhhmiyyyy.ss}
• mm – Month
• dd – Date
• hh – 24 hour format
• mi – Minutes
• yyyy – Year
• ss – seconds
For example, to set system date to Jan 31st 2009, 10:19 p.m, 53
seconds
# date 013122192009.53
You can also change system date using set argument as shown below.
# date 013122192009.53
# date +%Y%m%d -s “20090131”
# date -s “01/31/2009 22:19:53″
# date -s “31 JAN 2009 22:19:53″
# date set=”31 JAN 2009 22:19:53″

To set the time only:
# date +%T -s “22:19:53″
# date +%T%p -s “10:19:53PM”

Display Date and Time in a Specific Format

The following are different ways of displaying the current date and time
in various formats:
$ date
Thu Jan 1 08:19:23 PST 2009
$ date –date=”now”
Thu Jan 1 08:20:05 PST 2009
$ date –date=”today”
Thu Jan 1 08:20:12 PST 2009
$ date –date=’1970-01-01 00:00:01 UTC +5 hours’ +%s
18001
$ date ‘+Current Date: %m/%d/%y%nCurrent Time:%H:%M:%S’
Current Date: 01/01/09
Current Time:08:21:41
$ date +”%d-%m-%Y”
01-01-2009

The following are the different format options you can pass to the date
command:
• %D date (mm/dd/yy)
• %d day of month (01..31)
• %m month (01..12)
• %y last two digits of year (00..99)
• %a locale’s abbreviated weekday name (Sun..Sat)
• %A locale’s full weekday name, variable length
(Sunday..Saturday)
• %b locale’s abbreviated month name (Jan..Dec)
• %B locale’s full month name, variable length
(January..December)
• %H hour (00..23)
• %I hour (01..12)
• %Y year (1970…)

Display Past Date and Time

The following are various ways to display a past date and time:
$ date –date=’3 seconds ago’
Thu Jan 1 08:27:00 PST 2009
$ date –date=”1 day ago”
Wed Dec 31 08:27:13 PST 2008
$ date –date=”1 days ago”
Wed Dec 31 08:27:18 PST 2008
$ date –date=”1 month ago”
Mon Dec 1 08:27:23 PST 2008

$ date –date=”1 year ago”
Tue Jan 1 08:27:28 PST 2008
$ date –date=”yesterday”
Wed Dec 31 08:27:34 PST 2008
$ date –date=”10 months 2 day ago”
Thu Feb 28 08:27:41 PST 2008

Display Future Date and Time

The following examples shows how to display a future date and time.
$ date
Thu Jan 1 08:30:07 PST 2009
$ date –date=’3 seconds’
Thu Jan 1 08:30:12 PST 2009
$ date –date=’4 hours’
Thu Jan 1 12:30:17 PST 2009
$ date –date=’tomorrow’
Fri Jan 2 08:30:25 PST 2009
$ date –date=”1 day”
Fri Jan 2 08:30:31 PST 2009
$ date –date=”1 days”
Fri Jan 2 08:30:38 PST 2009
$ date –date=”2 days”

Sat Jan 3 08:30:43 PST 2009
$ date –date=’1 month’
Sun Feb 1 08:30:48 PST 2009
$ date –date=’1 week’
Thu Jan 8 08:30:53 PST 2009
$ date –date=”2 months”
Sun Mar 1 08:30:58 PST 2009
$ date –date=”2 years”
Sat Jan 1 08:31:03 PST 2011
$ date –date=”next day”
Fri Jan 2 08:31:10 PST 2009
$ date –date=”-1 days ago”
Fri Jan 2 08:31:15 PST 2009
$ date –date=”this Wednesday”
Wed Jan 7 00:00:00 PST 2009.

CHAPTER 3 : ESSENTIAL LINUX COMMANDS : SORT : UNIQ : CUT

Sort Command
Sort command sorts the lines of a text file. Following are several
practical examples on how to use the sort command based on the
following sample text file that has employee information in the format:
employee_name:employee_id:department_name.
$ cat names.txt
Emma Thomas:100:Marketing
Alex Jason:200:Sales
Madison Randy:300:Product Development
Sanjay Gupta:400:Support
Nisha Singh:500:Sales
Sort a text file in ascending order
$ sort names.txt
Alex Jason:200:Sales
Emma Thomas:100:Marketing
Madison Randy:300:Product Development
Nisha Singh:500:Sales
Sanjay Gupta:400:Support
Sort a text file in descending order
$ sort -r names.txt
Sanjay Gupta:400:Support
Nisha Singh:500:Sales
Madison Randy:300:Product Development
Emma Thomas:100:Marketing
Alex Jason:200:Sales
Sort a colon delimited text file on 2nd field (employee_id)
$ sort -t: -k 2 names.txt
Emma Thomas:100:Marketing
Alex Jason:200:Sales
Madison Randy:300:Product Development
Sanjay Gupta:400:Support
Nisha Singh:500:Sales
Sort a tab delimited text file on 3rd field (department_name) and
suppress duplicates
$ sort -t: -u -k 3 names.txt
Emma Thomas:100:Marketing
Madison Randy:300:Product Development
Alex Jason:200:Sales
Sanjay Gupta:400:Support
Sort the passwd file by the 3rd field (numeric userid)
$ sort -t: -k 3n /etc/passwd | more
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin

lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
Sort /etc/hosts file by ip-address
$ sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n /etc/hosts
127.0.0.1 localhost.localdomain localhost
192.168.100.101 dev-db.thegeekstuff.com dev-db
192.168.100.102 prod-db.thegeekstuff.com prod-db
192.168.101.20 dev-web.thegeekstuff.com dev-web
192.168.101.21 prod-web.thegeekstuff.com prod-web
Combine sort with other commands
• ps –ef | sort : Sort the output of process list
• ls -al | sort +4n : List the files in the ascending order of the filesize.
i.e sorted by 5th filed and displaying smallest files first.
• ls -al | sort +4nr : List the files in the descending order of the
file-size. i.e sorted by 5th filed and displaying largest files first.

Uniq Command
Uniq command is mostly used in combination with sort command, as
uniq removes duplicates only from a sorted file. i.e In order for uniq to
work, all the duplicate entries should be in the adjacent lines. The
following are some common examples.
1. When you have an employee file with duplicate entries, you can do
the following to remove duplicates.
$ sort namesd.txt | uniq
$ sort –u namesd.txt

2. If you want to know how many lines are duplicates, do the following.
The first field in the following examples indicates how many duplicates
where found for that particular line. So, in this example the lines
beginning with Alex and Emma were found twice in the namesd.txt file.
$ sort namesd.txt | uniq –c
2 Alex Jason:200:Sales
2 Emma Thomas:100:Marketing
1 Madison Randy:300:Product Development
1 Nisha Singh:500:Sales
1 Sanjay Gupta:400:Support
3. The following displays only the entries that are duplicates.
$ sort namesd.txt | uniq –cd
2 Alex Jason:200:Sales
2 Emma Thomas:100:Marketing

Cut Command
Cut command can be used to display only specific columns from a text
file or other command outputs.
The following are some of the examples.
Display the 1st field (employee name) from a colon delimited file
$ cut -d: -f 1 names.txt
Emma Thomas
Alex Jason
Madison Randy
Sanjay Gupta
Nisha Singh

Display 1st and 3rd field from a colon delimited file
$ cut -d: -f 1,3 names.txt
Emma Thomas:Marketing
Alex Jason:Sales
Madison Randy:Product Development
Sanjay Gupta:Support
Nisha Singh:Sales
Display only the first 8 characters of every line in a file
$ cut -c 1-8 names.txt
Emma Tho
Alex Jas
Madison
Sanjay G
Nisha Si
Misc Cut command examples
• cut -d: -f1 /etc/passwd Displays the unix login names for all the
users in the system.
• free | tr -s ‘ ‘ | sed ‘/^Mem/!d’ | cut -d” ” -f2

Displays the total memory available on the system.

Chapter 2 : Essential Linux Commands : Find

Find Command

find is frequently used command to find files in the UNIX filesystem
based on numerous conditions. Let us review some practice examples of find command.

Syntax: find [pathnames] [conditions]

#How to find files containing a specific word in its name?
The following command looks for all the files under /etc directory with mail in the filename.

# find /etc -name “*mail*”

How to find all the files greater than certain size?
The following command will list all the files in the system greater than
100MB.
# find / -type f -size +100M

How to find files that are not modified in the last x
number of days?
The following command will list all the files that were modified more
than 60 days ago under the current directory.
# find . -mtime +60

How to find files that are modified in the last x number of
days?
The following command will list all the files that were modified in the last
two days under the current directory.
# find . –mtime -2
How to delete all the archive files with extension *.tar.gz
and greater than 100MB?

# find / -type f -name *.tar.gz -size +100M -exec ls -l {} \;
# find / -type f -name *.tar.gz -size +100M -exec rm -f {} \;

How to archive all the files that are not modified in the
last x number of days?
The following command finds all the files not modified in the last 60
days under /home/jsmith directory and creates an archive files under
/tmp in the format of ddmmyyyy_archive.tar.
# find /home/jsmith -type f -mtime +60 | xargs tar -cvf
/tmp/`date ‘+%d%m%Y’_archive.tar`