Python IF ELSE Code Write in One Line

python if else one line code

 

There are many people like you very curious to know how to write simple one liner Python IF ELSE statements. Because of indentation in Python space has its own value and one extra space can crash your program.

To make your lengthy code looks short and easy human understandable you can write IF-ELSE in one line too.

python if-else statements

Observe the syntax specified in this example. You can’t re-arrange anything, not even single space! This is ordinary Python if-else statements.

age=int(input(“Enter your age:”))

print(“Your age is “, age)

if age>18:

    print(“You are eligible to vote”)

else:

    print(“You are NOT eligible to vote”)

If Else in one line!

Let’s try to put all IF-ELSE statements in ONE LINE without having any issue with the indentation and generates the same result.

python IF ELSE one liner code

Output

python IF ELSE one liner code output

Few more examples to understand how you can implement one liner IF-ELSE Statements.

  • Set value for variable “b” –  IF a=25 then set b=20 ELSE set b=10

>>> a=10

>>> b=20 if a==25 else 10

>>> print(b)

10

  • Set value for variable “b” –  IF var=”OneLineCode” then set b=20 ELSE set b=10

>>> var=”OneLineCode”

>>> b=20 if var==”OneLineCode” else 10

>>> print(b)

20

  • Set value for variable “b” –  IF var=”not_matching_str” then SET b=”New str” ELSE Set b=”TheEnd”

>>> var=”matching”

>>> b=”New str” if var==”not_matching_str” else “TheEnd”

>>> print(b)

TheEnd

>>> print(var)

matching

>>> 

The one liner IF-ELSE code can be used in the loop statements to make your code easily readable.

Read More: Python – IF-ELSE;   For-Loop;   While-Loop

Tips and Tricks: SUPERPUTTY CHANGE FONT SIZE OR BACKGROUND COLOUR

Casey Neistat hacked by Burger King on Twitter

Casey Neistat on Burger King twitter news

The New York youtuber star, Casey Neistat got hacked by Burger King! Yes, you heard right! That tough guy got clean bowled in front of Burger King’s smart strategic move on twitter.

There was incident happened when someone from Burger King who handles their official social handles played very smart game. They selected few high-profile twitter accounts and  gone through all the tweets, I am assuming just by scrolling down 10 years back blindly and liked their few random tweets.

Here is the mind game! Let’s consider someone randomly liked your post which is 10 years older then probably you will be more curious to know reason behind it. Why would someone does this?

Same has happened with Casey Neistat, they randomly liked his few tweets from 2010 and in general just for the curiosity Casey asked, why Burger King is liking his tweets from 2010 and twitter BHOOOM!

Here is the exact line where it all started!

Why is Burger King liking my 8 years old tweets?

This was the simple question Casey asked in general on twitter and it got so viral. This is so obvious! Probably Casey forget how many followers he has on twitter, Facebook and YouTube.

Casey Neistat question to Burger King twitter

On top of that there are many people who has huge number of followers responded on this tweet helped to trend Burgers on twitter

Casey’s Appeal:

Casey is known for his Youtube Channel “Casey Neistat”, not to forget he has 10+ Millions of subscribers. He creates an interesting videos and post it on his channel almost on daily basis.

When he came to know that this is kind of some promotional trick played by Burger King, he immediately posted video to explain the situation and asked Burger King to give him something in return.

Casey is very kind person, he has appealed  burger king to help poor or needy people in return. After all Burger King got all the free footage and advantage by influencing Casey. 

Here are some stats which shows how much free footage Burger King has got after this incident.

free footage stats

Burger King twitter impression value by liking Casey Neistat tweets

Python WHILE Loop & FOR Loop Control Flow Statements

Python while loop and for loop control flow statements

In this article we are going through Loop control flow statements in python. It is almost same as other programming language such as C, C++ or java etc.

Sometimes you must take control on program execution to run same set of code in a loop to get the desired output. To control the program execution, we have special utilities or statements called as “Control flow statements” 

The loop statements while or for allow us to execute a statement(s) over and over. A loop is controlled by a boolean expression that determines how many time statements can be executed.

Python has two primitive loop commands:
           1. While – loop
           2. For – loop

1. WHILE Loop

While condition is true keep running the loop and exit as soon as the condition becomes false. The conditional while loop syntax is the same as for if-else and elif statements.

Syntax:

while (conditional test):

    <statement1>

    <statement2>

    . . . .

    <last statement>

Example:

Python while loop statement code
Output:

Python while loop statement output

2. For Loop

Another loop statement – for, is best for when you determine in advance how many times you need to execute the block of statements placed in the loop.

It allows you to perform an operation on each element in a list or character in a string.

Syntax:

for in :

   

   

   


There are two types of for loops in python, first one is List – for loop and second one is          Range – for loop.

2.1 List – for loop

It’s very simplest method, all you need to do to specify complete list of items and it will be available in the loop.

Example:

python for loop statement code

Output:

python for loop statement output

Let’s take one more example-

for integer in [0, 1, 2]:

    print (“Integer :” + str(integer))

    print (“Integer Multplication :”+ str(integer * integer))

Output:

Integer :0

Integer Multplication :0

Integer :1

Integer Multplication :1

Integer :2

Integer Multplication :4

2.2 Range – for loop

For loop with range, gives you flexibility to use the appropriate range of values and important thing is you can control that range using available options along with for.

Syntax:

for var in range (start_pos, end_pos, steps):

    statement(s)

  • start_pos: Start position value should be excluded from range value when you specify value for steps otherwise it can be counted.
  • end_pos: End position must be excluded from range value.
  • steps: Steps value controls the range values.

Example:

python for loop range code
python for loop range output

Few more examples which will clear all your doubts if you have any!

Ex. 1

for i in range (1, 20, 2):

    print (“Range value :” + str(i))

Output:

Range value :1

Range value :3

Range value :5

Range value :7

Range value :9

Range value :11

Range value :13

Range value :15

Range value :17

Range value :19

Ex. 2

for i in range (20, 0, -2):

    print (“Range value :” + str(i))

Output:

Range value :20

Range value :18

Range value :16

Range value :14

Range value :12

Range value :10

Range value :8

Range value :6

Range value :4

Range value :2

 

Read More: Python break, continue and pass statements

Python IF ELSE & Nested IF-ELSE Control Flow Statements

Python IF ELSE and Nested IF ELSE control flow statements

In this article we are going through Python IF ELSE control flow statements. It is almost same as other programming language such as C, C++ or java etc.

The program default executes sequentially but sometimes you have to take control on program execution to get the desired output. To control the program execution, we have special utilities or statements called as “Control flow statements” 

Control
Flow IF-ELSE Statements:

               1. IF-ELSE

               2. Nested IF-ELSE

1. Python IF ELSE

IF-ELSE statement used to evaluate the condition and executes the block of statements based on results which is either YES (true) or NO (false)

General Syntax:

If (Condition)

Statement(s)

Else

Statement(s)

Syntax in Python: 

It is bit different syntax in python to write IF-ELSE conditional control flow statements. A blank spaces (indentation) is very important factor while writing code in python, especially if-else or nested if-else multiple conditional blocks. One extra blank space can kill your program!

if:

            <statement(s)>

else:

            <statement(s)>

Note: Please make a note, if-else statements are in lower case characters. In case if you write it in upper case, then you will get syntax error which is most common mistake people are doing. Python is very case sensitive language! 

Example:

Python IF ELSE Statement code

Output:

Python IF ELSE Statement code output

2. Nested IF ELSE

Simple IF-ELSE works fine but if you have multiple conditions and each one of them depends on another condition then Nested If-ELSE is very useful and effective.

It gives you flexibility to write multiple conditions and control your set of commands. It also helps to minimize the execution time as if one condition is true then it will skip further conditions and saves the time.

Syntax:

if :

            <statement(s)>

elif :

            <statement(s)>

elif :

            <statement(s)>

else:

            <statement(s)>

Be careful with if-elif-else statements, they must appear as-is in lower case and ELSE IF should be elif only. In case if you write any character in uppercase or elseif instead of elif, then you will defintely gets syntax error. Python is very case sensitive language and doesn’t allow any syntax violation.

Example:

Python Nested IF ELSE Statement code
Python Nested IF ELSE Statement output

Read More: Python For Loop and While Loop

World’s “lightest” Satellite by Indian Space Research Organization (ISRO)

Lightest satellite first ever in the space!

Indian Space Research Organization (ISRO) known to the world as a champion in developing cheapest but high-quality satellites in their unique and innovative ways. Now one more title ISRO has got after placing world’s lightest satellite into space.  

India’s Polar Satellite Launch Vehicle (PSLV-C44) successfully placed Microsat-R and Kalamsat-V2 satellites into their designated orbits.

The PSLV-C44 lifted off at 23:37  (IST) on 24th January 2019 from the Sriharikota in its 46th flight.

 

ISRO Satellite kalamsat PSLV

Kalamsat-v2

The man behind the Indian space research is no more in this universe but his “wings of fire” still flying all around the space. His name very well known to global – Dr. APJ Abdul Kalam. 

Kalamsat-V2 names after the former president and one of India’s greatest scientist late Dr APJ Abdul Kalam. After successful launch of Kalamsat-V2, it seems vision of the late Dr APJ Abdul Kalam has transited into the Indian young generation.  

Feature of this satellite is –  it is just 1.26KG weight. At post-launch address, Chairman Dr K Sivan didn’t forget to mention that this is the lightest weight satellite ever successfully placed in the orbit and this is done by us – INDIA – he noted. The cost of this satellite is as usual very low around 12Lakh.

ISRO satellite kalamsat v2 team

Most importantly, this satellite was designed and built by bunch of Indian students who worked with a private organization called Space Kidz India in Chennai. It took only 6 days to build this satellite by student though it was required complete 6 years of hard work and preparations. 

NASA has already tried to launch a 64-gram earlier version of the Kalamsat nicknames “gulab jamun” in year 2017 but never succeeded but ISRO did it at its first go!

ISRO PSLV Kalamsat satellite launch

Dr K Sivan congratulated Kalamsat-V2 team for their perfection in making satellites. 

“We must strive for science-oriented India. ISRO is open to all   students across India. We want students to bring their satellites to us   and we will launch them. Young scientists will shape the future of   India.”

This message was very strong and effective from ISRO as it shown the results in the form the KalmsatV2 and I am sure it might hit positive vibes & attraction towards scientist in students mind.

If you are a student(individual) or group of students and have some idea or already implemented something/InProgress which will survive in the space and provides us valuable information, then here is the opportunity! ISRO is waiting for you!

Along with KalamsatV2 there was one more satellite placed into space named as – Microsat-R that will be used to take high resolution photos of Earth for defense research.

Prime Minister of India Congratulates to Indian scientist!

PM Narendra Modi tweet on ISRO Kalamsat satellite launch

What is Program, Algorithm and Flowchart

what is Program ?

A program is a collection of instructions that performs a specific task when executed by a computer.An algorithm and flowchart are the basic components of programming.

Programs can be written either in one of high level language which executes slowly, or low level language (machine or assembly language) which executes very faster.

main()

{

printf(“hello world!!n”);

}

Python Compiler

It converts instructions into machine language. We write a code is in the format of human readable or in a plane English text of course by following some specific set of rules associated with that programming language. Computer need something to translate those text into machine readable format. 

Compiler translate your program that is source code (high level programming language) into machine code (or assembly language or low level language) to create an executable program.

Source code ——–à>>Compiler
——–à>> machine code

Program Compiler Design

Keywords

A keyword is a reserved identifier used by the language to describe a special feature. It is used to declare an object, or in a function body to describe the statement executed. It can not be used as a constant or variable or any other identifier name. 

For instance, if you use any reserved keywords in python like pass or class then check here what complications could introduce in your simple program.

Algorithm

An algorithm is a step by step guide written to solve the problem in a very simple way or in a plane English language. It is a roadmap of your thoughts – where to start, what to start, how should proceed and wrapping up your program.  It represents process or flow of your program in a simple words.

The main motto of designing of an algorithm to have clear understanding on requirement and its solution. Anyone from outside who doesn’t familiar with programming language can understand overall picture of your so complicated program logic in a very generic way. An algorithm is used to create the flow chart.

Examples

Let’s take an example: Write an algorithm to add two numbers!

               1. Start

               2. Take two numbers (x and y)

               3. Apply formula to perform your task: (ans=x+y)

             In this example; we can add two numbers (x and y) and store result in                     variable “ans”.

               4. Display result

               5. End

Here is one more – Write an algorithm to check whether seller has profit or loss.

               1. Start

               2. Collect the product data from seller- Its selling price and actual cost.

               3. Apply formula to calculate profit

              (Profit = selling price – product cost)

               4. Take a decision –

               – if profit is greater than zero; that means seller got some profit in                             business

               – if profit is less than zero; that means seller got some loss in business

               – if profit is equal to zero; that means seller neither got profit nor loss.

               5. Display result

               6. End

Everyone has our own views to look at the problem and of course has the different ways to solve it. Here is one of the alternatives to check profit or loss.

            3.   Apply formula to calculate profit

                  (Profit = selling price – product cost)

               4. Take a decision –

               – if selling price is greater than product cost; that means seller got some                     profit in business

               – if selling price is less than product cost; that means seller got some loss                   in business

               – if selling price is equal to product cost; that means seller neither got                       profit nor loss

Likewise, you can write algorithm of your program in a very simple way. 

Try this one on your own in comment section below – Write an algorithm to calculate average of five numbers? Or maybe this one – To check whether entered numbers are even or odd?

Flow Chart

The flow chart is a graphical or symbolic representation of your algorithm, process or workflow.

This diagram representation demonstrates a solution model of a given program. Flow charts are being effectively used in analyzing, designing and managing processes in the big projects. It is essential part of the program especially when you are dealing with the complex requirement. 

Flow chart has its common alternative names include: flowchart, process flowchart, functional flowchart, process map, process chart, functional process chart, business process model, process model, process flow diagram, workflow diagram, etc.

Symbolic representation

Overview of common symbolic representation of flow chart:

Program flow chart symbols

Let’s try to build flow chart of our second example algorithm – to check whether seller has profit or loss.

Program Flow chart

What are your thoughts on “What is program, algorithm and flow chart” ?

What is in Facebook’s 10 year challenge ?

facebook's 10 year challenge reaction on twitter

You might have seen very interesting and funny pictures on internet under 10 year challenge trend. It is known to you that January month comes every year along with 10 year challenge on social media-especially on Facebook & twitter. 

This year stands out because of social media numbers – there are millions of people took this challenge  & shared photo on social media.

Current trend may trigger an interest in you to take this challenge too in case if you haven’t.

Perhaps, some hidden agendas or strategy, experts seen in this campaign especially these days where artificial intelligence blowing around.

Everyone is curious about  Artificial intelligence and want to build something cool out of it  but is it okay to play with your data or sell your pictures ?

Facebook is already getting millions of pictures every day on top of that such campaign gives them chance to look at your old picture and new picture- compare it -come up with the generic algorithm which will tell you how you will look in next 10 years! Super cool. Isn’t it?

But how do you feel if someone makes a billion-dollar business by selling your pictures without knowing you and you don’t know how/what purposes they will use your data. You will not have any control on your own pictures.

Facebook’s announcement on twitter

While Facebook has officially stated, the 10 year challenge is a user-generated meme that started on its own and denied their involvement!

facebook on 10 year challenge

AI, ML & DL

The big giants are always in the top list to concur fresh technologies. It is not always easy to take a grab on such technologies and come out with the meaningful products/solutions. 

The concepts – Artificial Intelligence(AI), Machine Learning(ML), Deep Learning(DL) required lots of hard work and many organizations are ready to invest in it.

The big hurdle in this process is, it required huge amount of data to build something new and test its result. Google Assistant, Apple’s Siri, Alexa, etc are the few but mostly popular  products interacting with you,  collecting data globally and trying to improve every second.

facial recognition

The video processing,  imaging processing or facial recognition are also part of AI and comes under trending subjects. An autopilot mode in Tesla car is the best example of image processing.

Looks something fishy in  this 10-year challenge and seems it is getting triggered intentionally every year by Facebook to collect the old and latest pictures to build face recognition algorithm. 

I am more afraid to see Google in that context. Almost everyone has the google account and happily using google photo application, but do you know Google has your all the photos & documents.

Now you might say you have full control on your data through GDPR and so, but Does it really true? 

As a normal person we always have a doubt on such things, irrespective of an effort taken by government to implement data protection policy lows and principles because of scandals like Facebook–Cambridge Analytica data scandal.

Now here is the situation to decide whether want to be part of such campaign. oh, more specifically – you want to be part of such scandal! Or Not!!

People reacted on twitter – 

facebook's 10 year challenge reaction on twitter

LINUX/UNIX SHELL SCRIPT TO ARCHIVE LOGS BY FLUSHING OUT ITS CONTENT

You probably wondering, how log files to be archived especially when your system is running 24/7 and continuously updating the log files. In a traditional way, we could do this by
moving out all the log files from its original location to Archive directory and cleaning up there. You might want to check this log archiving script.

Please note – if your log files are continuously updated by your application and if you try to archive the logs by moving in another folder then there are high chances to get the error in the application.

The solution for this problem could be run this script outside business hours by taking 5-10 minutes downtime. But we should always look for BEST solution and it is not guaranteed that you will always get the system downtime approval from client. 

So, here is the trick – Without taking any actual downtime we could first copy all the files to another folder and just flush out the content of log files present in original location.

If you don’t want to go through all the details about this archiving process, then you may directly jump into script.

What this script does?

          1.       COPY: Copy all your log files from main LOG directory to Archive directory.

          2.       MAKE DIR: Before you copy your logs to Archive directory, create new folder under Archive directory and then move everything inside that directory.

          3.       DELETE CONTENT: After copying all the files into Archive, flush out the content of log files present in original directory.

           4.       CLEAN UP ARCHIVE: Remove all logs files present under archive folder which are older than N days (for example, 7 days)

 

This is your main LOG directory where all your log files present. Also make sure you should have the archive directory.

     cd /local/apps/WebServer/Web ls

     Log      Archive

     LOG=/local/apps/WebServer/Web/Log

     Archive=/local/apps/logs/WebServer/Web/Archive

Variables used in the script:

LEVROOT: This is your root directory, in this example mu root directory is “/local/apps/WebServer/Web”

LOG: This is your actual log directory. In this example my LOG directory is

“/local/apps/WebServer/Web/Log”

ARCHIVE: This is your archive directory. In this example my ARCHIVE directory is

“/local/apps/WebServer/Web/Archive”

You could manage your archive folder by creating new folder (through script) each day and then move everything there in Archive-Subdirectory.

DATE: This is date variable which will hold todays date

TIME: This is time variable which will hold current time.

            1. Define your variables

          LEVROOT=/local/apps/WebServer/Web

          DATE=$(date +%d%m%y)

          TIME=$(date +%H%M)

          ARCHIVE=“$LEVROOT/Archive/$DATE-$TIME”

          LOG=”$LEVROOT/Log”

          2. Search the log files (along with the sub directories) under Archive which are older than 7 days and delete it. (of course, you can change that limit to 2 days or 15 days, etc. depending on your requirement.)

          find $LEVROOT/Archive/* -mtime +7 -type d -print -exec rm -R {} ;

You can verify this command by just listing down the file names. Run this command:

          find $LEVROOT/Archive/* -mtime +7

          3. Create subdirectory under Archive directory to manage your archived files efficiently. This is very useful if large numbers of log files getting generated under LOG directory.

          mkdir $ARCHIVE

           4. COPY your log files into Archive directory.

           find $LOG -type f -print -exec cp -p {} $ARCHIVE ;

           5. CLEAR the content of log files present in your main LOG directory.

           find $LEVROOT/*.* -type f -exec sh -c ‘>”{}”‘ ;

 

LINUX/UNIX LOG ARCHIVE SCRIPT

Here is the complete files archiving script considering scenario discussed above. If you have any doubts in the script, then you may look at the scenario again or just leave your comment below.

#———————————————————————–

# Script for archiving of logs by flushing out its content

# Script          : logs_Archive.sh

# 02-01-2019 : Linux/Unix Admin

#———————————————————————-

#!/bin/sh

# Varibales Used:

 

LEVROOT=/local/apps/WebServer/Web

DATE=$(date +%d%m%y)

TIME=$(date +%H%M)

ARCHIVE=“$LEVROOT/Archive/$DATE-$TIME”

LOG=”$LEVROOT/Log”

 

#CLEAN up Archive directory

find $LEVROOT/Archive/* -mtime +7 -type d -print -exec rm -R {} ;

 

mkdir $ARCHIVE

 

#COPY files to archive directory

find $LOG/*.* -type f -print -exec cp -p {} $ARCHIVE ;

 

#remove content from log files

find $LOG/*.* -type f -exec sh -c ‘>”{}”‘ ;

 

echo $ARCHIVE

echo $LOG

Linux/Unix Parameterized Shell Script to Archive logs

You have already known about the tradition but more effective log archiving script, if you don’t then you might want to check this script first.

In case if you have many different jobs running and they are creating huge files under its individual directory then let’s modify little bit our script so we can use the same script for all the jobs instead of creating multiple script

PARAMETERIZED UNIX/LINUX SHELL SCRIPT

This is very easy way of reusing your script just by-passing parameter outside from the script. We need to provide the parameter(s) while running the script.

In our example, lets consider we have multiple directories under /local/apps/BatchServer/

You can make this script very generic by passing “directory name”. Assume, you have sub-directories like –  MyDIStudioJob_1MyDIStudioJob_2MyDIStudioJob_3, etc. You can pass these directory name from outside and it is referred and replaced by  $1 in the script.

 

Now your LEVROOT will become –  LEVROOT=/local/apps/BatchServer/$1

PS- Make sure you have Log and Archive folders created under each sub-directory.

LOG ARCHIVING SCRIPT

 

#——————————————————

# Script for archiving of logs 

# Script         : logs_Archive.sh

# Parameter   : $1: Sub-directory Name

# 02-01-2019 : Linux/Unix Admin

#——————————————————-

#!/bin/sh

# Varibales Used:

 

LEVROOT=/local/apps/Batchserver/$1

DATE=$(date +%d%m%y)

TIME=$(date +%H%M)

ARCHIVE=”$LEVROOT/Archive/$DATE-$TIME”

LOG=”$LEVROOT/”

 

find $LEVROOT/Archive/* -mtime +7 -type d -print -exec rm -R {} ;

 

mkdir $ARCHIVE

find $LOG -type f -print -exec mv {} $ARCHIVE ;

 

echo $ARCHIVE

echo $LOG

EXECUTE SCRIPT

Let’s say you want to run this script for job number 1 which has logs generated under subdirectory MyDIStudioJob_1

      ./logs_Archive.sh MyDIStudioJob_1

Or may be you want to run for Job number 3 as –

      ./logs_Archive.sh MyDIStudioJob_3 

 

PS: This script is all about moving the long files into Archive and clean up there. But if you have job or application running 24/7 then you can’t move your log files from original directory. You may want to check this best possible solution here in another blog post to handle such scenarios. 

Linux Shell Script to Archive log files

Most common task to manage your file system for Linux or Unix administrator to set up the script which will take care of your log files (or any output files).

There are many ways to archive log files, but I feel it is very hard to find out best one.

No hurdles, here you find one of the BEST, more generic & robust solution and it can be applicable to all your scenarios.

If you don’t want to go through all the details about archive script, then you may directly jump into log archive script

Let’s take a following common scenario as an example.

  1. Move all your log files from main LOG directory to Archive directory
  2. Before you move your logs to Archive directory, create new folder under archive directory and then move everything inside that directory.
  3. Remove all logs files which are older than N days (for example, 7 days)

And you are good to manage your files without any manual interventions
or weekly/monthly activity.

This is your main LOG directory where all your log files present. Also make sure you should have the archive directory.

cd /local/apps/BatchServer/MyDIStudioJob1 ls

Log      Archive

LOG=/local/apps/BatchServer/MyDIStudioJob1/Log

Archive=/local/apps/BatchServer/MyDIStudioJob1/Archive

 

Variables used in the script:

LEVROOT: This is your root directory, in this example my root directory is “/local/apps/BatchServer/MyDIStudioJob1

LOG: This is your actual log directory. In this example my LOG directory is

/local/apps/BatchServer/MyDIStudioJob1/Log

ARCHIVE: This is your archive directory. In this example my ARCHIVE directory is “/local/apps/BatchServer/MyDIStudioJob1/Archive” 

You could manage your archive folder by creating new folder (through script) each day and then move everything there in Archive-Subdirectory.

DATE: This is date variable which will hold todays date

TIME: This is time variable which will hold current time.

          1. DEFINE your variables

          LEVROOT=/local/apps/BatchServer/MyDIStudioJob1

          DATE=$(date +%d%m%y)

          TIME=$(date +%H%M)

          ARCHIVE=“$LEVROOT/Archive/$DATE-$TIME”

          LOG=”$LEVROOT/”

        2.  Search and Delete files: Search the log files (along with the sub directories)  under Archive which are older than 7 days and delete it. (of course, you can              change that limit to 2 days or 15 days, etc. depending on your requirement.)

There many linux commands to search the files or sub directories but I’ve                found “find” command very easy and convenient to search files and “rm”              will clean up files or subdirectories. 

          find $LEVROOT/Archive/* -mtime +7 -type d -print -exec rm -R {} ;

You can verify this command by just listing down the file names. Run this                command: 

          find $LEVROOT/Archive/* -mtime +7

        3. Create Subdirectory:Create subdirectories under Archive directory to manage your archived files efficiently. This is very useful if large numbers of log files getting generated under LOG directory.

          mkdir $ARCHIVE

            4. Move Log files: Move your files into Archive directory. Again, “find” command is very effective here as well.

               find $LOG -type f -print -exec mv {} $ARCHIVE ;

 

LINUX/UNIX LOG ARCHIVE SCRIPT:

Here is the complete files archiving script considering scenario discussed above. If you have any doubts in the script, then you may look at the scenario again or just leave your comment below.

#—————————————————————-

# Script for archiving of logs.

# Script          : logs_Archive.sh

# 02-01-2019 : Linux/Unix Admin

#—————————————————————–

#!/bin/sh

# Varibales Used:

 

LEVROOT=/local/apps/Batchserver/MyDIStudioJob1

 

DATE=$(date +%d%m%y)

TIME=$(date +%H%M)

ARCHIVE=”$LEVROOT/Archive/$DATE-$TIME”

LOG=”$LEVROOT/”

 

find $LEVROOT/Archive/* -mtime +7 -type d -print -exec rm -R {} ;

 

mkdir $ARCHIVE

find $LOG -type f -print -exec mv {} $ARCHIVE ;

 

echo $ARCHIVE

echo $LOG