Shell Script Questions and Answers

Can you tell me the various stages of a Linux process, it passes through?

A Linux process normally goes through four major stages in its processing life.

Here are the 4 stages of the Linux process.

Waiting: Linux Process waiting for a resource.

Running: A Linux process is currently being executed.

Stopped: A Linux Process is stopped after successful execution or after receiving a kill signal.

Zombie: A Process is said to be ‘Zombie’ if it has stopped but is still active in the process table.

 

 

How to print “Hello World” through a script in linux

$ echo “Hello World”

#!/bin/bash

echo “Hello World”

You can run the script in two ways. One way is by using the bash command and another is by setting execute permission to bash file and run the file. Both ways are shown here.

$ bash First.sh or shell First.sh

$ chmod a+x First.sh

$ ./First.sh

 

 

How to use comments and multi-line comments in Shell scripting

# symbol is used to add a single-line comment in the bash or shell script.

#!/bin/bash

# Add two numeric value

You can use the multi-line comment by adding :’ and ending with ‘

#!/bin/bash

: ‘

The following script calculates

the square value of the number, 5. ‘

((area=5*5)) echo $area

 

 

How to use While Loop in the shell scripts

#!/bin/bash

a=0

while [ $a -lt 10 ]

do

echo $a

(( a++ ))

done

 

 

How to use For Loop in Scripts

In the below example, for loop will iterate 5 times and print all values of the variable.

#!/bin/bash

for i in 1 2 3 4 5

do

echo “Welcome $i times”

done

 

 

How to get User Input in the shell scripts

‘read’ command is used to take input from the user in bash. Create a file named ‘user_input.sh’ and add the following script for taking input from the user. Here, one string value will be taken from the user and display the value by combining other string values.

#!/bin/bash

echo “Enter Your Name”

read name

echo “Welcome $name to DevOps Learning.”

$ bash user_input.sh

 

 

How to use the if statement

Starting and ending block of this statement is defined by ‘if’ and ‘fi’.

Here, 10 is assigned to the variable, n. if the value of $n is less than 10 then the output will be “It is a one-digit number”, otherwise the output will be “It is a two digit number”. For comparison, ‘-it is used here. For comparison, you can also use ‘-eq’ for equality, ‘-ne’ for not equality and ‘-gt’ for greater than in bash script.

#!/bin/bash

n=11

if [ $n -lt 10 ]; then

echo “It is a one digit number”

else

echo “It is a two digit number”

fi

$ bash simple_if.sh

 

 

How to use if statement with AND logic:

Different types of logical conditions can be used in an if statement with two or more conditions. How you can define multiple conditions in an if statement using AND logic is shown in the following example.

‘&&’ is used to apply AND logic of the if statement.

Create a file named ‘if_with_AND.sh’ to check the following code. Here, the value of username and password variables will be taken from the user and compared with ‘admin’ and ‘secret’. If both values match then the output will be “valid user”, otherwise the output will be “invalid user”.

!/bin/bash

echo “Enter username”

read username

echo “Enter password.”

read password

if [[ ( $username == “admin” && $password == “secret” ) ]]; then

echo “valid user”

else

echo “invalid user”

fi

$ bash if_with_AND.sh

 

‘||’ is used to define OR logic in the if condition.

 

 

How to use else if statement:

The use of the else if condition is little different in bash than other programming language. ‘elif’ is used to define the else if condition in bash.

#!/bin/bash

echo “Enter your lucky number”

read n

if [ $n -eq 101 ]; then

echo “You got 1st prize”

elif [ $n -eq 510 ];

then

echo “You got 2nd prize”

elif [ $n -eq 999 ];

then

echo “You got 3rd prize”

else

echo “Sorry, try for the next time”

fi

Run the file with the bash command.

$ bash elseif_example.sh

 

 

How to get Arguments from Command Line:

Bash script can read input from command line argument like other programming language. For example, $1 and $2 variable are used to read first and second command line arguments. Create a file named “command_line.sh” and add the following script. Two argument values read by the following script and prints the total number of arguments and the argument values as output.

#!/bin/bash

echo “Total arguments : $#”

echo “1st Argument = $1”

echo “2nd argument = $2”

Run the file with bash command.

$ bash command_line.sh Linux learn

 

 

What is the significance of $# in the shell script?

$# shows the count of the arguments passed to the script.

 

 

What is the significance of $?

$? gives the exit status of the last command that was executed.

 

 

Write a script that add Two Numbers:

You can do the arithmetical operations in bash in different ways. How you can add two integer numbers in bash using double brackets is shown in the following script. Create a file named ‘add_numbers.sh’ with the following code. Two integer values will be taken from the user and printed as the result of the addition.

#!/bin/bash

echo “Enter first number”

read x

echo “Enter second number”

read y

(( sum=x+y ))

echo “The result of addition=$sum”

Run the file with bash command.

$ bash add_numbers.sh

 

 

How to create Functions and call with parameters in shell scripts

#!/bin/bash

Rectangle_Area() {

area=$(($1 * $2))

echo “Area is : $area”

}

Rectangle_Area 10 20

$ bash function_parameter.sh

 

 

How to Pass Return Value from Function:

The function, greeting() returns a string value into the variable, val which prints later by combining with other string.

#!/bin/bash

function greeting() {

str=”Hello, $name”

echo $str

}

echo “Enter your name”

read name

val=$(greeting)

echo “Return value of the function is $val”

 

 

Make a directory by checking existence:

If you want to check the existence of a directory in the current location before executing the ‘mkdir’ command then you can use the following code. ‘-d’ option is used to test whether a particular directory exists or not.

#!/bin/bash

echo “Enter directory name”

read ndir

if [ -d “$ndir” ]; then

echo “Directory exist”

else

`mkdir $ndir`

echo “Directory created”

fi

$ bash directory_exist.sh

 

 

How to Read a File:

You can read any file line by line in bash by using loop. Create a file named, ‘read_file.sh’ and add the following code to read an existing file named, ‘book.txt’.

#!/bin/bash

file=’first.sh’

while read line;

do

echo $line

done < $file

$ bash read_file.sh

 

 

How to test if File Exist:

You can check the existence of file in bash by using ‘-e’ or ‘-f’ option.

‘-f’ option is used in the following script to test the file existence. Create a file named, ‘file_exist.sh’ and add the following code. Here, the filename will pass from the command line.

#!/bin/bash

filename=$1

if [ -f “$filename” ]; then

echo “File exists”

else

echo “File does not exist”

fi

 

 

How to Send Email

You can send email by using ‘mail’ or ‘sendmail’ command. Before using these commands, you must install all necessary packages. Create a file named, ‘mail_example.sh’ and add the following code to send the email.

#!/bin/bash

Recipient=”admin@example.com”

Subject=”Greeting”

Message=”Welcome to our site”

`mail -s $Subject $Recipient <<< $Message`

Run the file with bash command.

$ bash mail_example.sh

 

 

Get Parse Current Date:

You can get the current system date and time value using `date` command. Every part of the date and time value can be parsed using ‘Y’, ‘m’, ‘d’, ‘H’, ‘M’ and ‘S’.

Create a new file named ‘date_parse.sh’ and add the following code to separate day, month, year, hour, minute, and second values.

#!/bin/bash

Year=`date +%Y`

Month=`date +%m`

Day=`date +%d`

Hour=`date +%H`

Minute=`date +%M`

Second=`date +%S`

echo `date`

echo “Current Date is: $Day – $Month – $Year”

echo “Current Time is: $Hour : $Minute : $Second”

Run the file with the bash command.

 

$ bash date_parse.sh

 

 

Sleep Command:

When you want to pause the execution of any command for a specific period of time then you can use the sleep command. You can set the delay amount by seconds (s), minutes (m), hours (h), and days (d). Create a file

named ‘sleep_example.sh’ and add the following script. This script will wait for 5 seconds after running.

#!/bin/bash

echo “Wait for 5 seconds”

sleep 5

echo “Completed”

Run the file with bash command.

$ bash sleep_example.sh

 

 

Example shell script that creates a Docker image and pushes it to a Docker registry:

#!/bin/bash

# Set variables for the Docker image and registry

DOCKER_IMAGE=myapp

DOCKER_TAG=latest

DOCKER_REGISTRY=myregistry.com

# Build the Docker image

docker build -t ${DOCKER_IMAGE}:${DOCKER_TAG} .

# Log in to the Docker registry

docker login ${DOCKER_REGISTRY}

# Tag the Docker image with the registry and version

docker tag ${DOCKER_IMAGE}:${DOCKER_TAG} ${DOCKER_REGISTRY}/${DOCKER_IMAGE}:${DOCKER_TAG}

# Push the Docker image to the registry

docker push ${DOCKER_REGISTRY}/${DOCKER_IMAGE}:${DOCKER_TAG}

This script first sets variables for the Docker image name, tag, and registry. It then builds the Docker image using the Dockerfile in the current directory and tags it with the image name and tag.

The script then logs in to the Docker registry using the docker login command. It tags the Docker image with the registry and version using the docker tag command, and pushes the image to the registry using the docker push command.

Note that this script assumes that the Dockerfile is in the current directory and that the Docker registry requires authentication. You may need to customize this script based on your specific use case.

 

 

Example shell script to build Java code using Gradle

#!/bin/bash

# Set variables for the Gradle project directory and Gradle executable

GRADLE_PROJECT_DIR=/path/to/gradle/project

GRADLE_EXECUTABLE=/usr/local/bin/gradle

# Change to the Gradle project directory

cd ${GRADLE_PROJECT_DIR}

# Run Gradle build

${GRADLE_EXECUTABLE} build

This script assumes that you have Gradle installed and configured on the system running the script. It sets the GRADLE_PROJECT_DIR variable to the path of the Gradle project, and the GRADLE_EXECUTABLE variable to the path of the Gradle executable.

The script then changes to the Gradle project directory using the cd command, and runs the Gradle build using the ${GRADLE_EXECUTABLE} build command.

You can customize this script based on your specific Gradle project structure and build process.

 

 

Example shell script to test Java code using JUnit:

#!/bin/bash

# Set variables for the Java project directory and JUnit executable

JAVA_PROJECT_DIR=/path/to/java/project

JUNIT_EXECUTABLE=/usr/local/lib/junit-platform-console-standalone.jar

# Change to the Java project directory

cd ${JAVA_PROJECT_DIR}

# Run JUnit tests

java -jar ${JUNIT_EXECUTABLE} –class-path build/classes/test:build/libs/* –scan-class-path

This script assumes that you have JUnit installed and configured on the system running the script. It sets the JAVA_PROJECT_DIR variable to the path of the Java project, and the JUNIT_EXECUTABLE variable to the path of the JUnit executable.

The script then changes to the Java project directory using the cd command, and runs the JUnit tests using the java command. The –class-path option specifies the classpath for the test classes and dependencies, and the –scan-class-path option tells JUnit to scan the classpath for test classes.

 

 

Example Shell script to list AWS images older than one year

You can use the AWS CLI and some basic shell commands in a script.

#!/bin/bash

# Get the current date in Unix timestamp format

current_date=$(date +%s)

# Get the list of image IDs and creation dates

image_info=$(aws ec2 describe-images –query ‘Images[*].[ImageId,CreationDate]’ –output text)

# Loop through each image and check if it is older than one year

while read -r image_id creation_date; do

# Convert the creation date to Unix timestamp format

creation_timestamp=$(date -d “$creation_date” +%s)

# Calculate the age of the image in seconds

age=$(($current_date – $creation_timestamp))

# If the image is older than one year (31536000 seconds), output its ID and age

if [ $age -gt 31536000 ]; then

echo “Image ID $image_id is older than one year (age: $(($age / 86400)) days)”

fi

done <<< “$image_info”

This script first gets the current date in Unix timestamp format using the date command. It then gets a list of all images in your AWS account, along with their creation dates, using the aws ec2 describe-images command with a custom –query parameter. The output is stored in the image_info variable.

The script then loops through each image in the output using a while read loop. For each image, it converts the creation date to Unix timestamp format using the date command, and calculates the age of the image in seconds by subtracting the creation timestamp from the current timestamp.

If the age of the image is greater than one year (31536000 seconds), the script outputs the image ID and its age in days using the echo command.

Note that you’ll need to have the AWS CLI installed and configured on your system for this script to work.

 

 

Example SHELL Script to store jenkins jobs config.xml

find /var/lib/jenkins/jobs/ -maxdepth 2 -type f -name “config.xml” -exec cp –parent {} . \;

name=`hostname`

tar -cvf ${name}.tar var/

gzip ${name}.tar

curl -sS -u $ARTIFACTORY_USER:$ARTIFACTORY_PASSWORD -X PUT $ARTIFACTORY_SERVER/artifactory/test-project/store/${name}.tar.gz -T ./${name}.tar.gz

if [ $? -eq 0 ]; then

echo “tar.gz file has been uploaded!!!”

else

echo “WARNING: Upload to articatory has failed!!!”

fi

 

 

Example Shell script to restore jenkins job using job’s config.xml file

name=`hostname`

echo $nameOfJob

pwd

ls -ltr config.xml

curl -s -XPOST “http://${name}:8080/createItem?name=${nameOfJob}” -u sericeacc@abc.com:${SVCCI_PASS} –data-binary @config.xml -H “Content-Type:text/xml”

Leave a Reply

Your email address will not be published. Required fields are marked *