Trending December 2023 # How To Use Scriptlet Tag In Jsp # Suggested January 2024 # Top 14 Popular

You are reading the article How To Use Scriptlet Tag In Jsp updated in December 2023 on the website We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 How To Use Scriptlet Tag In Jsp

Introduction to JSP Scriptlet

The following article provides an outline for JSP Scriptlet. JSP (Java Server Pages) Scriptlet is a tag that is used to write java source code to implement business logic. This Scriptlet tag is declared inside the _jspService() method. _jspService()method always create new object for every new request. So as Scriptlet tag is inside the _jspService() method it will also create new object for every new request.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Declaration tag

Expression tag

Scriptlet tag

Each tag has their own specification to insert the code in the JSP application. Declaration tag is used to declare variables and methods. Expression tag is used to display output of the JSP application. Scriptlet tag is used to include Java source code. Scriptlet tag is mostly used for Form action pages implementation.

How to use Scriptlet Tag in JSP?


Like <% out.println(“content”);


Plain Java for printing the output we write System.out.println() but in case of JSP we just write out.println() and System class automatically provided by JSP web container.

In JSP there are 9 implicit objects are there out is one among them.

Difference Between Declaration Tag and Scriptlet Tag

Given below is the difference between declaration tag and scriptlet tag:

Declaration Tag Scriptlet Tag

It can declare variables as well as methods. It can declare only variables not methods.

This tag is placed outside the _jspService() method. This tag is placed inside the _jspService() method.

It creates only one object for multiple requests. It creates multiple objects for multiple requests.

Note: We can write JSP code inside html page also, we can save JSP page with .html extension if html tags contains. If plain JSP code then we need to save with .jsp extension.

Examples of JSP Scriptlet

Given below are the examples mentioned:

Example #1

Display out.

JSP Code: Out.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" h1 { color:green; text-align: center; } p { color: blue; font-size: 25px; border: solid 3px brown; } <% out.print( "JSP (Java Server Pages) Scriptlet is a tag used write java source code to implement business logic. This Scriptlet tag declared inside the _jspService() method. _jspService() method always create new object for every new request. So as Scriptlet tag is inside the _jspService() method it will also create new object for every new request. There 3 types of tag in JSP 1. Declaration tag 2. Expression tag 3. Scriptlet tag Each tag has their own specification to insert the code in the JSP application. Declaration tag is used to used to declare variables and methods. Expression tag is used to display output of the JSP application. Scriptlet tag is used for include Java source code.");


Example #2

HTML to JSP action for display company name.

h1 { color: green; text-align: center; } input { color: blue; font-size: 22px; height: 50px; width: 300px; } button { color: white; background: brown; font-size: 25px; } label { font-size: 22px; }

JSP Code: company.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" h1 { color: orange; text-align: center; } p { color: navy; font-size: 25px; border: solid 3px brown; } <% String name = request.getParameter("company"); out.print("I am working in " + name);


Before Submit:

After Submit:


Inside HTML page we enter company name and once we submit the details then action go to chúng tôi file this company will display there.

Example #3

User Sign Up.

h1 { color: green; text-align: center; } label { font-size: 22px; color: green; }

JSP Code: User.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" h1 { color: red; text-align: center; } p { color: green; font-size: 25px; border: solid 3px blue; } <% String name = request.getParameter("name"); String email = request.getParameter("email"); String gender = request.getParameter("gender"); String country = request.getParameter("country"); out.print("My Country is " + country);


Before Sign Up:

After Sign Up:


Scriptlet tag in JSP is used to include Java source code. It is always creating new object for each request. This purpose of this scriptlet tag is to develop form action applications.

Recommended Articles

This is a guide to JSP Scriptlet. Here we discuss the introduction, how to use scriptlet tag in JSP along with examples. You may also have a look at the following articles to learn more –

JSP Scripting Elements

JSP Life Cycle

What is JSP?

JSP Redirect

You're reading How To Use Scriptlet Tag In Jsp

Jstl (Jsp Standard Tag Library) Tutorial: Core & Custom Tags

In this JSTL tutorial, we will see how using different JSTL tags will make JSP coding easier.

In this tutorial, you will learn-

What is JSTL?

JSTL stands for Java server pages standard tag library, and it is a collection of custom JSP tag libraries that provide common web development functionality. JSTL is a standard tag library of the JSP.

Advantages of JSTL

Standard Tag: It provides a rich layer of the portable functionality of JSP pages. It’s easy for a developer to understand the code.

Code Neat and Clean: As scriplets confuse developer, the usage of JSTL makes the code neat and clean.

Easier for humans to read: JSTL is based on XML, which is very similar to HTML. Hence, it is easy for the developers to understand.

Easier for computers to understand: Tools such as Dreamweaver and front page are generating more and more HTML code. HTML tools do a great job of formatting HTML code. The HTML code is mixed with the scriplet code. As JSTL is expressed as XML compliant tags, it is easy for HTML generation to parse the JSTL code within the document.

JSTL Core Tags

The core tags are most frequently used tags in JSP. They provide support for


Conditional logic

Catch exception

url forward

Redirect, etc.

To use core tags we need to define tag library first and below is the syntax to include a tag library.

Syntax :


prefix can be used to define all the core tags and

uri is the library of taglib from which it is imported

Let see some of the core tags in detail,

1. Out:

Result of expression is displayed in the out tag

It can directly escape the XML tags. Hence, they are not evaluated as actual tags


Here value represents information to the output, and it is mandatory

Default is failure to output information, and it is not mandatory

escapeXML – It is true if it escapes XML characters.



<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

Explanation of the code:

Code Line 3: This taglib prefix is required for all tags and prefix added is ‘c’. Hence, it can be used as a prefix for all coretags.

Code Line 12: Here we are using coretag out with the prefix “c” and this out will print the value in the expression tag. Hence, output will be name

When you execute the above code, you get the following output:


We are getting the value as a name from the core tag “out” which will print in the output stream.

2. Catch

It catches any throwable exception which occurs in the body and shows as output.

It is used for handling the errors and to catch them.


Here var represents the name of the variable, which will hold throwable exception.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1" The Exception is : ${guruException}

Explanation of the code:

Code Line 3: This taglib prefix is required for all tags and prefix added is ‘c’ hence it can be used as a prefix for all coretags

Code Line 11-13: Coretag catch is used to catch the exception and print the exception. Here the exception is raised when 10/0 and that exception has name “guruException”.

Code Line 14: We are printing the “guruException”.

When you execute the code, you will get the following output:


We are getting Arithmetic Exception as /by zero, and it is printed in the output using variable “guruException”

3. Import

We can import another file contents into a JSP page like we did in JSP include action.

Here we can also include URL and contents will be displayed on that page.


Here var is a variable name which is an identifier, which will hold the filename/uri.

uri is relative filename or uriname.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

Explanation of the code:


Code Line 3: This taglib prefix is required for all tags and prefix added is ‘c’ hence it can be used as a prefix for all coretags

Code Line 11-12: Here we are importing coretag_jsp32.jsp file into this file using import tag

Code Line13: Here we are printing the file coretag_jsp32.jsp using out tag.

When you execute the above code, you get the following output.


Coretag_jsp32 is printed in the output as this file was imported in coretag_jsp31.jsp.

4. forEach

It is used to iterate the number of elements in series of statements.

It is same as a Java forloop.


Here var represents variable name which will hold counter name

Begin represents counter begin value

End will represent its end value


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

Explanation of the code:

Code Line 3: This taglib prefix is required for all tags and prefix added is ‘c’ hence it can be used as a prefix for all coretags

Code Line 11-13: Here we use “forEach” loop where the variable name is “gurucount”, which has begun count as 5 and end count as chúng tôi are printing the variable gurucount which has numbers starting from 5 to 10.

When you execute the code, you get the following output


The output we are getting is starting from 5 to 10.

5. If

It is used for Testing conditions.

If the tag is used to test a condition whether it is true or not based on this, the block of code would be executed.


Here if the condition is true then series of statements are executed.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

Explanation of the code:

Code Line 3: This taglib prefix is required for all tags and prefix added is ‘c’ hence it can be used as a prefix for all coretags

Code Line 11: Here we are setting the variable named as count to 100

Code Line 12-14: Here we are using “if condition” where we are checking whether the count is equal to 100. It is equal to 100 then we get the output as “The count is 100.”

When you execute the above code, you get the following output


As the “if” condition is true, we get the output as “The count is 100”.

6. redirect:

It is used for redirecting the current page to another URL by providing the relative URL of this tag.

It supports context relative URLs


Here url is relative url to which it has to be redirected and context name of the local web application.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

Explanation of the code:

Code Line 3: This taglib prefix is required for all tags and prefix added is ‘c’ hence it can be used as a prefix for all coretags

When you execute the above code, you get the following output;


We get the output chúng tôi url which is redirected by coretag_jsp6.jsp

JSTL Custom Tags

It is a user-defined JSP language element.

When JSP is translated into a servlet, custom tag is converted into a class which takes action on an object and is called as a tag handler.

Those actions when the servlet is executed are invoked by the web container.

To create the user-defined custom tag, we need to create the tag handler which will be extending the SimpleTagSupport and have to override doTag() method.

We need to create TLD where we need to map the class file in TLD.

Advantages of custom tags in JSP:

Portable – An action described in a tag library must be usable in any JSP container.

Simple – Unsophisticated users must be able to understand and use this mechanism.Vendors of JSP functionality must find it easy to make it available tousers as actions.

Expressive – The mechanism must support a wide range of actions, includingnested actions, scripting elements inside action bodies, creation, use andupdating of scripting variables.

Usable from different scripting languages – Although the JSP specificationcurrently only defines the semantics for scripts in the Java programming language, we want to leave open the possibility of other scripting languages.

Built upon existing concepts and machinery– We do not want to reinvent whatexists elsewhere. Also, we want to avoid future conflicts whenever we canpredict them


Consider we are creating testGuru tag and we can usetaghandlertestTag class, which will override doTag() method.

Class testTag extends SimpleTagSupport{ public void doTag()}

Also, we will have to map this testTag class in TLD (Tag Library Descriptor) as JSP container will automatically create a mapping between the class file and uri which has been mentioned in the TLD file.

JSP Tag Interface

This class will have to extend SimpleTagSupport class.

This class will have to override doTag() method which is part of SimpleTagSupport class (overriding is a method which is inherited from parent class).

This interface is a sub interface of JSPTag interface.

It provides methods to perform at the start and end of the tag.

Also, we need to map this class in TLD i.e. Tag Library descriptor

We are considering in the example below

Method of Tag Interface

doTag() is a method which we need to override which will have the contents for the tag.

It takes the current JSP Context using getJSPContext()



<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


package demotest; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; import*; public class guruTag extends SimpleTagSupport{ public void doTag() throws JspException,IOException { JspWriter out = getJspContext().getOut(); out.println("Guru Tag"); } }

Explanation of the code:

Code Line 6:guruTag class is extending SimpleTagSupport class which is present in chúng tôi jar

Code Line 7: Here we are overriding doTag() method which throws JspException and IOException.

Code Line 9-10: In this method, the code will be embedded to custom tag which will be called. We are taking an object of JspWriter, and that will print “Guru Tag.”


Code Line 6: Here name of the custom tag is “guruTag.”

Code Line 7:Tag class is taghandlerclass,i.e., It takes full path of the handler file which includes the directory path of the location of the file.


Code Line 3:This taglib prefix is required for all tags and prefix added is ‘ex’ hence it can be used as a prefix for all coretags and uri is chúng tôi which maps the tag handler.

Code Line 11: Here we are defining the custom tag “guruTag”, which will call the handler class doTag() method and the code within it will be executed.

When you execute the above code, you get the following output


We get the output as “GuruTag” from chúng tôi i.e. TagHandler, which overrides doTag() method and which print “Guru Tag” as an output.


In this section, we learnt about JSP standard tag library in which we did core tags and custom tags.

Core tags include for, if, redirect, import, catch tags which were tags used for basic purposes in JSP.

Also, we did custom tags wherein we can define the tags and use it in JSP

How To Add Spoiler Tag To Discord Images

How to add Spoiler Tag to Discord images

Adding a spoiler tag to images on Discord is a simple task. If you have added photos before during a conversation, then you may have noticed the option without fully realizing it. Follow these steps to add a Discord Spoiler Tag:

Open Discord

Navigate to the relevant chat

Add spoiler text to image

Write a message and send it off along with the photo.

If you are using either the desktop or the web version of the Discord app, you need not worry because sending a spoiler photo is possible on both.

1] Open Discord

Open the Discrod app on either computer or the web.

To begin, open the Discord app from your computer

Alternatively, visit the official website on the web.

Ensure you are logged in with your credentials before we can move forward to the next step.

2] Navigate to the relevant chat

We now want to select the Discord chat where the spoiler image must be shared.

Look to the left of Discord where youll see a list of chats

Locate the image you want to send, then select it.

Hit the Enter key on your keyboard.

4] Add spoiler to image

Hover over the newly added photo.

5] Write a message and send it off along with the photo.

Write a message and send it off along with the photo.

How to mark an image as a Spoiler on Discord mobile

Many users prefer the mobile version of Discord due to its convenience and overall ease of use. Now, in terms of adding the spoiler tag to a photo, it will work on both Android and iOS devices.

Open Discord on your phone or tablet

Go to the chat

Select the image you want to send

Add the spoiler tag

Send photo

1] Open Discord on your phone or tablet

First, locate where Discord is on your device, then tap the icon to open it.

2] Go to the chat and select plus icon

Open the chat from the left panel in Discord.

tap the “+” (plus) icon in the bottom-left corner of your chat

3] Select the image you want to send

From within this area, find the picture you want to send.

Select it from the list of options

Do not hit the Send button, but instead, tap outside of the image area in order to return to the chat screen.

4] Add the spoiler tag

The next thing we want to do here is to add the Spoiler tag to the photo.

Tap the image in order to open it in full size.

From beneath the photo, then, you will want to enable “Mark as Spoiler.”

Tap the back button right away to return to the chat screen.

5] Send photo

Now it is time to send the Spoiler photo to the person on the other end of the chat.

Add a message that acts as a description without giving away the contents of the picture.

Finally, tap the Send button at the bottom-right to complete the task.

We should note that this feature is not only available for private chat, but also in channels as well.

Read: Stop Discord from launching at Startup in Windows

What is the Discord app used for? What is the difference between Discord and WhatsApp?

Discord and WhatsApp are similar, but they are not the same. You see, WhatsApp is an instant messaging service with Voice over IP features, while Discord is more akin to a social media platform. In that sense, Discord has more in common with Facebook and Telegram than WhatsApp due to all the impressive features it brings to the table.

Apple In October Expectations: Apple Tag, 16

Even though September was a busy month for Apple, the year isn’t over just yet. Now that we’re officially in October, expect a new round of hardware and software releases from Apple. Ranging from the oft-rumored Apple Tag to the release of macOS Catalina, there’s a lot to look forward to — and it could all culminate in an October Apple event.

Apple October event

While Apple has not officially announced that it will hold an October event this year, there’s plenty of precedent. Last year, Apple held a special event in New York City to unveil the all-new iPad Pro as well as updates to the Mac lineup.

Could the same type of event occur this year? It’s certainly possible. Read on as we round up everything we expect from Apple in October.

16-inch MacBook Pro

Perhaps the product that people are most looking forward to is the 16-inch MacBook Pro. We’ve heard quite a bit about it so far, and several rumors have suggested a release date sometime in October and a starting price at around $3,000.

The 16-inch MacBook Pro is rumored to be the same physical size as the 15-inch MacBook Pro, but will feature smaller bezel sizes in order to fit the larger display. That display will feature a 3072×1920 resolution, according to supply chain reports.

Perhaps most notable, however, are the rumors that say the 16-inch MacBook Pro will drop Apple’s controversial butterfly keyboard. Reliable Apple analyst Ming-Chi Kuo has said that the 16-inch MacBook will be the first Mac to return to scissor switch keys.

This means you should expect greater key travel, as well as improved reliability, thanks to a new glass fiber that will supposedly help reinforce the keys.

In terms of power, a supply chain report suggested that the new MacBook Pro will feature 9th-gen Intel Coffee Lake-H processors. These are the same processors used by the current 15-inch MacBook Pro. That same report also indicated that the 16-inch MacBook Pro will be a replacement for the 15-inch model, suggesting they won’t coexist in Apple’s lineup.

An Apple event in October seems like the likely place for Apple to announce the 16-inch MacBook Pro — if it’s indeed coming in 2023 like rumors have suggested. It’s always possible that the release has been delayed, but hopefully we’ll learn more this month.

Read everything we know about the 16-inch MacBook Pro in our full guide right here.

Mac Pro

Apple announced the new Mac Pro and Pro Display XDR at WWDC in June. The website for the Mac Pro indicates that the machine will be available “this fall,” but details beyond that are unknown.

The new Mac Pro features an all-new design and an incredible amount of power inside. In conjunction with the new Mac Pro, Apple will also release the Pro Display XDR this fall, marking its return to the standalone display market.

The last day of fall is December 20, so Apple has quite a bit of time to release the new made-in-America Mac Pro while still meeting its original deadline. If Apple were to hold an October event, we’d at least expect an update on when to expect the Mac Pro, if not a firm release date.

Read everything we know about the Mac Pro in our full guide.

Other Mac updates

The Mac mini received a massive upgrade last year, so we don’t expect much, if anything, to change this year. The iMac and iMac Pro, however, are both due for an upgrade, whether it be a physical redesign or just under-the-hood improvements.

iPad Pro refresh

Coupled with the launch of iPadOS 13 last month, we expect Apple’s focus on the iPad Pro to continue in October.

The iPad Pro just got a major refresh in 2023 with an all-new design, more power than ever, and a new Apple Pencil. This year, rumors suggest that Apple will bring the same triple-lens camera setup that we see on the iPhone 11 Pro to the iPad Pro.

While the iPad Pro is not necessarily a common photography tool, the triple-lens camera does enable vastly improved augmented reality capabilities. It would also make sense for Apple to unify its “Pro” hardware with the same camera technology.

Other than the new triple-lens camera, it’s likely that Apple will give the iPad Pro a performance bump. It currently features the A12X Bionic processor, while the iPhone 11 features the A13 Bionic. If history is any indication, this would mean the 2023 iPad Pro might feature the A13X Bionic processor.

Apple Tag

As 9to5Mac has reported several times, Apple is developing a personal item tracker similar to the popular Tile products. What this means is that you’ll be able to attach Apple’s physical item tracker to any belonging, such as your wallet, backpack, keys, and more, and then track those items via the Find My application on Mac and iOS.

Furthermore, Apple Tag will also be able to leverage the massive iOS user base to ensure that it is always in range of a connected iPhone or other Apple device. Users will also be able to receive notifications when their iPhone gets too far away from the tag.

The iPhone 11 and iPhone 11 Pro both include Apple’s U1 Ultrawideband location chip. The U1 location chip is what powers the new AirDrop feature in iOS 13.1, but it is also expected to work in tandem with the Apple Tag. This would enable users to have access to the incredibly accurate location data of their item tracker with spatial awareness capabilities.

Read everything we know about Apple’s item tracker in our full guide.


iOS 13.2: Apple has been releasing new versions of iOS 13 at a quick pace recently. The next version on its way will likely be iOS 13.2, with the new Deep Fusion camera technology. It’s unclear if this will be released to the public in October, but beta testing will take place this month.

macOS Catalina: The final major OS release from Apple in 2023 will be macOS Catalina. This update introduces several new applications, such as Music, Podcasts, and TV, and opens the door for new third-party Mac apps from developers. It’s possible that macOS Catalina could be released as early as this Friday, October 4. Learn more about macOS Catalina in our full guide right here.

HomePod: Apple delayed several notable HomePod features until “later this fall,” including multi-user support and Handoff for Apple Music. Whether or not these features materialize in October remains to be seen.

More possibilities for an Apple October event

Augmented Reality: iOS 13 is full of evidence that Apple is continuing its development of augmented reality features. It’s still unclear how these frameworks might manifest for the end user, but it’s clearly an important area of development for Apple.

Updated Apple TV: The Apple TV is becoming more important than ever for Apple, thanks to the launch of Apple Arcade and Apple TV+. Last month, we detailed several reasons why a new Apple TV could be arriving this year. With Apple TV+ launching on November 1, it would make perfect sense for Apple to unveil the new Apple TV hardware at an event in October.

Apple over-ear headphones: Bloomberg has reported that Apple is developing a new over-ear pair of Apple headphones for launch in 2023. This would be Apple’s first foray into over-ear headphones, and presumably exist separately from Beats. If these headphones are coming in 2023, expect them to be announced this month.

Apple October event wrap up

Despite a September that saw the launch of the iPhone 11, iPhone 11 Pro, and Apple Watch Series 5, October has the potential to be just as busy for Apple. With hardware such as the 16-inch MacBook Pro and Apple Tag and software such as macOS Catalina in the pipeline, there’s a lot to be excited about if you’re an Apple fan.

With all of these announcements coming, it’s likely that Apple will hold an October event. Last year, Apple held its October event on October 30, so we’re still a few weeks away from any sort of confirmation.

FTC: We use income earning auto affiliate links. More.

How To Use Emojis In Linux

Emojis have become a popular way to express emotions and add a bit of personality to text conversations in today’s Internet age.

Many folks expect to have some way of viewing and using emojis no matter the operating system they’re on since they already get to use them on their mobile devices and social media networks.

If you’re coming from a macOS or Windows 10 experience, you get to use this feature out of the box. Alas, the support for emojis on the Linux desktop is largely below par.

Depending on your distribution, you might be able to see monochrome representations of emoji characters by default. For example, Fedora 25 can display these symbols while also allowing you to quickly search, select and input emojis using a keyboard shortcut.

Since not all distros have this feature built in, let’s take a look at some distro-agnostic ways you can view and input emoji from your Linux PC.

Install an Emoji Font

The Symbola font can display a wide range of emoji symbols as monochrome glyphs. You should install it if it’s not packaged by default in your distribution.

Packages like ttf-ancient-fonts on Ubuntu-based distributions and gdouros-symbola-fonts on Fedora-based ones make it easy to get the Symbola font onto your Linux desktop.

Run the following commands to install ttf-ancient-fonts in Ubuntu 16.04 and other Ubuntu-based distributions:


apt-get install


To display color emojis in Linux, you need to install an emoji font. A good option to try is the EmojiOne Color Font which uses glyphs from the free EmojiOne set.

At this time it will only show color emoji in Firefox, Thunderbird and other Gecko-based programs. Other applications will fall back to black and white glyphs, but in general these will be much better than the ones you get from the Symbola fonts package.

Here’s how to install it in Ubuntu and Ubuntu-based distributions:


apt-add-repository ppa:eosrei




apt-get update


apt-get install


If you prefer Twitter’s emoji design, install Twitter Color Emoji Font instead:


apt-add-repository ppa:eosrei




apt-get update


apt-get install


For other distributions, installation instructions can be found on the font’s Github page.

Input Emoji with EmojiOne Picker

The best way to input emoji will largely depend on your preferred desktop environment. A good solution is to use the EmojiOne Picker applet for Ubuntu.

This program adds a categorised emoji applet to your desktop’s taskbar or panel which makes it easy for you to find, copy and paste emojis.

Although designed specifically for Ubuntu and the Unity desktop, it has been reported to work on other distributions and several DEs such as GNOME, KDE Plasma, MATE, XFCE, Pantheon and Cinnamon.

Installation instructions for your distribution can be found on the project’s Github page.

Once you have it installed, launch the program from your application launcher. The picker applet will be added to your system tray.

To use the picker, simply choose your emoji from the drop-down menu to copy it to your clipboard, and then paste it wherever you want.


Ayo Isaiah

Ayo Isaiah is a freelance writer from Lagos who loves everything technology with a particular interest in open-source software. Follow him on Twitter.

Subscribe to our newsletter!

Our latest tutorials delivered straight to your inbox

Sign up for all newsletters.

By signing up, you agree to our Privacy Policy and European users agree to the data transfer policy. We will not share your data and you can unsubscribe at any time.

How To Use Bash Wait Command In Linux

In the world of shell scripting, process management and synchronization are critical. The Bash wait command is a quick and easy way to coordinate and regulate the execution flow of several processes. Understanding how to use the wait command correctly can improve the efficiency and dependability of your shell scripts greatly. In this article, we will deconstruct the Bash wait command, looking at its features, typical use cases, and best practices in Linux.


Access to the command line/terminal.

Administrator (sudo) privileges.

A text editor, such as Vim or Nano.

Syntax for Bash wait command

SyntaxDescriptionwaitWaits for a child process to terminate.wait [-n] job_idWaits for the job with the specified job_id to terminate. The -n option causes wait to return immediately if the job is already terminated.wait -nWaits for the next background job to chúng tôi wait Command Syntax

Wait command

When working with wait in bash scripts, there are three more parameters to be aware of:

The ampersand sign (&) following a command denotes a background job.

$! returns the PID of the most recent background process. When working with several background processes, remember to save the previous PID in a variable.

$? displays the last process’s exit status.

To show how these three factors interact, launch a terminal window and type:

sleep 10 & echo $! echo $?

The $! argument holds the background process PID, while $? stores the exit status. The exit status 0 indicates that the command was successful.

Single Process Wait

Begin by opening the terminal and running the following background process:

sleep 10 &

Confirm that the job is executing in the background by typing:

jobs -l

Note: If the job is marked as finished, consider increasing the sleep time to more than 10 seconds.

Use the wait command without any parameters to pause until the procedure is finished:


The terminal is waiting for the background process to complete.

The terminal prints the Done message after 10 seconds (due to sleep 10).

Single Process Bash wait

Use the wait command to specify when a background process within a script must execute.

For example, in a text editor, enter the following code:

#!/bin/bash echo Background process & echo First message echo Second message wait echo Third message ~ ~

If the background process does not complete the first and second processes, the wait command causes a pause to wait for the background process to finish the second process before proceeding to the third process.

Save the script as Change the permissions in the terminal to make the script executable:

sudo chmod +x

Use the following commands to run the script:

./ [email protected]:~$ ./ First process second process Background process Third process [email protected]:~$

The background process finishes once the wait instruction is executed, and the script proceeds.

Multiple Processes Bash Wait

Open a text editor and paste the following script with several processes:

#!/bin/bash sleep 10 & sleep 15 & sleep 5 & echo $(date +%T) wait echo $(date +%T) ~ ~

The script prints the current time before and after the wait command. Without any parameters, the application just waits for all processes to complete.

Close the file and save the script as Make the script executable next:

sudo chmod +x

Finally, execute the program with:


Because the operations are running in the background, all three are finished in fifteen seconds.

Run the same script to test the following use cases:

Add the -n argument to wait. Only the fastest process completes, and the script stops in ten seconds.

Add the job ID to specify which job the script should wait for. Wait%1 pauses for process 1 (sleep 10) to complete.

Multiple Processes Bash Wait With PID

When working with many processes, utilize the PID to identify a process. The following example script illustrates a single use case:

#!/bin/bash echo "Process 1 lasts for 2s" && sleep 2 & PID=$! echo "Process 2 lasts for 3s" && sleep 3 & echo "Current time $(date +%T)" wait $PID echo "Process 1 ended at time $(date +%T) with exit status $?" wait $! echo "Process 2 ended at time $(date +%T) with exit status $?" ~ ~

The script should be saved as Make the script executable by typing:

sudo chmod +x

Run the script to see the results:

./ [email protected]:~$ ./ Process 1 lasts for 2s Process 2 lasts for 3s Current time 15:56:22 Process 1 ended at time 15:56:24 with exit status © Process 2 ended at time 15:56:25 with exit status © [email protected]:~$

The script completes the first process in two seconds (due to sleep 2) and the second process in three seconds. Both operations run concurrently and take three seconds to complete.

Also read: You might also find useful our guide on How to Change Directory in Linux Using cd Command.


Update the detailed information about How To Use Scriptlet Tag In Jsp on the website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!