🕷️ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 14 (from laksa146)

2. Crawled Status Check

Query:
Response:

3. Robots.txt Check

Query:
Response:

4. Spam/Ban Check

Query:
Response:

5. Seen Status Check

ℹ️ Skipped - page is already crawled

đź“„
INDEXABLE
âś…
CRAWLED
29 days ago
🤖
ROBOTS ALLOWED

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH1 months ago
History dropPASSisNull(history_drop_reason)No drop reason
Spam/banPASSfh_dont_index != 1 AND ml_spam_score = 0ml_spam_score=0
CanonicalPASSmeta_canonical IS NULL OR = '' OR = src_unparsedNot set

Page Details

PropertyValue
URLhttps://www.redhat.com/en/blog/bash-scripting-while-loops
Last Crawled2026-03-17 04:37:36 (29 days ago)
First Indexed2024-12-17 09:32:20 (1 year ago)
HTTP Status Code200
Meta TitleLinux scripting: 3 how-tos for while loops in Bash
Meta DescriptionShell scripting, specifically Bash scripting, is a great way to automate repetitive or tedious tasks on your systems. Why type when you can schedule and run ...
Meta Canonicalnull
Boilerpipe Text
Shell scripting, specifically Bash scripting, is a great way to automate repetitive or tedious tasks on your systems. Why type when you can schedule and run scripts in a hands-free manner? One of the many scripting constructs is the loop. A loop is a section of code that picks up data or generates data and then performs some operation on the data and then begins the process over again until some condition is met, the script is disrupted, or when input data is exhausted. When you use Bash scripting , sometimes it is useful to perform actions using some form of loops. [ Readers also liked:  Five ways to use redirect operators in bash ] The basic loop commands in Bash scripts are for and while . for loops are typically used when you have a known, finite list, like a series of numbers, a list of items, or counters. while loops can be used with lists but are also useful for conditions that do not have a known limit. You can use it to run commands while a condition is true (or invert the logic and run it while the condition is false). So, while (pun intended) there are different ways to perform loops, in this article, I focus on examples using while loops. 1. A simple while loop Imagine that you're installing a huge application, and you're concerned that it may eventually use too much space on the file system. Instead of running df in a separate terminal, you can run a simple command to monitor the disk utilization every second. This allows you to interrupt the installation process if you see that it will hit that limit. while true do   df -k | grep home   sleep 1 done In this case, you're running the loop with a true condition, which means it will run forever or until you hit CTRL-C. Therefore, you need to keep an eye on it (otherwise, it will remain using the system's resources). Note : If you use a loop like this, you need to include a command like sleep to give the system some time to breathe between executions. Running anything non-stop could become a performance issue, especially if the commands inside the loop involve I/O operations. 2. Waiting for a condition to become true There are variations of this scenario. For example, you know that at some point, the process will create a directory, and you are just waiting for that moment to perform other validations. You can have a while loop to keep checking for that directory's existence and only write a message while the directory does not exist. If you want to do something more elaborate, you could create a script and show a more clear indication that the loop condition became true: #!/bin/bash while [ ! -d directory_expected ] do    echo "`date` - Still waiting"     sleep 1 done echo "DIRECTORY IS THERE!!!" 3. Using a while loop to manipulate a file Another useful application of a while loop is to combine it with the read command to have access to columns (or fields) quickly from a text file and perform some actions on them. In the following example, you are simply picking the columns from a text file with a predictable format and printing the values that you want to use to populate an /etc/hosts file. Here the assumption is that the file has columns delimited by spaces or tabs and that there are no spaces in the content of the columns. That could shift the content of the fields and not give you what you needed. Notice that you're just doing a simple operation to extract and manipulate information and not concerned about the command's reusability. I would classify this as one of those "quick and dirty tricks." Of course, if this was something that you would repeatedly do, you should run it from a script, use proper names for the variables, and all those good practices (including transforming the filename in an argument and defining where to send the output, but today, the topic is while loops). #!/bin/bash cat servers.txt | grep -v CPU | while read servername cpu ram ip do    echo $ip $servername done [ Learn the basics of using Kubernetes in this free cheat sheet . ]  Wrap up while loops are useful in scripts that depend on a certain condition to be true or false, but you can also use them interactively to monitor some condition. The important things to remember are: Always be clear about what is the condition to end the loop. If that is something that you expect to do yourself with a CTRL-C , then keep an eye on your command. Think about how fast you want each loop cycle to be repeated. If you do any operation that involves I/O inside the loop, that becomes a critical aspect of planning. With that in mind, have fun while you can.
Markdown
[Skip to content](https://www.redhat.com/en/blog/bash-scripting-while-loops#rhdc-main-content) ## Navigation Menu AI - ### Overview - [AI news](https://www.redhat.com/en/blog/channel/artificial-intelligence) - [Technical blog](https://developers.redhat.com/blog?field_tax_product_target_id%5B37288%5D=37288&extIdCarryOver=true&intcmp=7013a000003Sl59AAC&sc_cid=RHCTG0250000454096&_gl=1%2A1jal9i8%2A_gcl_au%2ANjU2NDY1NTAwLjE3NjQ2MTY4NTU.&percmp=RHCTG0250000466729) - [Live AI events](https://www.redhat.com/en/events/ai) - [Inference explained](https://www.redhat.com/en/ai/inference/what-you-should-know-about-inference) - [See our approach](https://www.redhat.com/en/artificial-intelligence) - ### Products - [Red Hat AI Enterprise](https://www.redhat.com/en/products/ai/enterprise) - [Red Hat AI Inference Server](https://www.redhat.com/en/products/ai/inference-server) - [Red Hat Enterprise Linux AI](https://www.redhat.com/en/products/ai/enterprise-linux-ai) - [Red Hat OpenShift AI](https://www.redhat.com/en/products/ai/openshift-ai) - [Explore Red Hat AI](https://www.redhat.com/en/products/ai) - ### Engage & learn - [Learning hub](http://docs.redhat.com/en/learn/ai) - [AI topics](https://www.redhat.com/en/topics/ai) - [AI partners](https://catalog.redhat.com/categories/ai#ai-partners) - [Services for AI](https://www.redhat.com/en/services/consulting/red-hat-consulting-for-ai) Hybrid cloud - ### Platform solutions - [Artificial intelligence](https://www.redhat.com/en/hybrid-cloud-solutions/ai) Build, deploy, and monitor AI models and apps. - [Linux standardization](https://www.redhat.com/en/hybrid-cloud-solutions/linux-standardization) Get consistency across operating environments. - [Application development](https://www.redhat.com/en/hybrid-cloud-solutions/application-development) Simplify the way you build, deploy, and manage apps. - [Automation](https://www.redhat.com/en/hybrid-cloud-solutions/automation) Scale automation and unite tech, teams, and environments. - ### Use cases - [Virtualization](https://www.redhat.com/en/hybrid-cloud-solutions/virtualization) Modernize operations for virtualized and containerized workloads. - [Digital sovereignty](https://www.redhat.com/en/products/digital-sovereignty) Control and protect critical infrastructure. - [Security](https://www.redhat.com/en/solutions/trusted-software-supply-chain) Code, build, deploy, and monitor security-focused software. - [Edge computing](https://www.redhat.com/en/products/edge) Deploy workloads closer to the source with edge technology. - [Explore solutions](https://www.redhat.com/en/hybrid-cloud-solutions) - ### Solutions by industry - [Automotive](https://www.redhat.com/en/solutions/automotive) - [Financial services](https://www.redhat.com/en/solutions/financial-services) - [Healthcare](https://www.redhat.com/en/solutions/healthcare) - [Industrial sector](https://www.redhat.com/en/solutions/industrial-sector) - [Media and entertainment](https://www.redhat.com/en/solutions/media-entertainment) - [Public sector (Global)](https://www.redhat.com/en/solutions/public-sector) - [Public sector (U.S.)](https://www.redhat.com/en/solutions/public-sector/us) - [Telecommunications](https://www.redhat.com/en/solutions/telecommunications) ### [Discover cloud technologies](https://www.redhat.com/en/hybrid-cloud-console) Learn how to use our cloud products and solutions at your own pace in the Red Hat® Hybrid Cloud Console. Products - ### Platforms - [Red Hat AI](https://www.redhat.com/en/products/ai) Develop and deploy AI solutions across the hybrid cloud. - [Red Hat Enterprise Linux](https://www.redhat.com/en/technologies/linux-platforms/enterprise-linux) Support hybrid cloud innovation on a flexible operating system. - [Red Hat OpenShift](https://www.redhat.com/en/technologies/cloud-computing/openshift) Build, modernize, and deploy apps at scale. - [Red Hat Ansible Automation Platform](https://www.redhat.com/en/technologies/management/ansible) Implement enterprise-wide automation. - ### Featured - [Red Hat OpenShift Virtualization Engine](https://www.redhat.com/en/technologies/cloud-computing/openshift/virtualization-engine) - [Red Hat OpenShift Service on AWS](https://www.redhat.com/en/technologies/cloud-computing/openshift/aws) - [Microsoft Azure Red Hat OpenShift](https://www.redhat.com/en/technologies/cloud-computing/openshift/azure) - [See all products](https://www.redhat.com/en/technologies/all-products) - ### Try & buy - [Start a trial](https://www.redhat.com/en/products/trials) - [Buy online](https://www.redhat.com/en/store) - [Integrate with major cloud providers](https://www.redhat.com/en/partners/certified-cloud-and-service-providers) - ### Services & support - [Consulting](https://www.redhat.com/en/services/consulting) - [Product support](https://www.redhat.com/en/services/support) - [Services for AI](https://www.redhat.com/en/services/consulting/red-hat-consulting-for-ai) - [Technical Account Management](https://www.redhat.com/en/services/support/technical-account-management) - [Explore services](https://www.redhat.com/en/services) Training - ### Training & certification - [Courses and exams](https://www.redhat.com/en/services/training/all-courses-exams) - [Certifications](https://www.redhat.com/en/services/certifications) - [Skills assessments](https://skills.ole.redhat.com/en) - [Red Hat Academy](https://www.redhat.com/en/services/training/red-hat-academy) - [Learning subscription](https://www.redhat.com/en/services/training/learning-subscription) - [Explore training](https://www.redhat.com/en/services/training-and-certification) - ### Featured - [Red Hat Certified System Administrator exam](https://www.redhat.com/en/services/training/ex200-red-hat-certified-system-administrator-rhcsa-exam) - [Red Hat System Administration I](https://www.redhat.com/en/services/training/rh124-red-hat-system-administration-i) - [Red Hat Learning Subscription trial (No cost)](https://www.redhat.com/en/services/training/learning-subscription/trial) - [Red Hat Certified Engineer exam](https://www.redhat.com/en/services/training/ex294-red-hat-certified-engineer-rhce-exam-red-hat-enterprise-linux) - [Red Hat Certified OpenShift Administrator exam](https://www.redhat.com/en/services/training/red-hat-certified-openshift-administrator-exam) - ### Services - [Consulting](https://www.redhat.com/en/services/consulting) - [Partner training](https://connect.redhat.com/en/training) - [Product support](https://www.redhat.com/en/services/support) - [Services for AI](https://www.redhat.com/en/services/consulting/red-hat-consulting-for-ai) - [Technical Account Management](https://www.redhat.com/en/services/support/technical-account-management) Learn - ### Build your skills - [Documentation](https://docs.redhat.com/en) - [Hands-on labs](https://www.redhat.com/en/interactive-labs) - [Hybrid cloud learning hub](https://cloud.redhat.com/learn) - [Interactive learning experiences](https://www.redhat.com/en/interactive-experiences) - [Training and certification](https://www.redhat.com/en/services/training-and-certification) - ### More ways to learn - [Blog](https://www.redhat.com/en/blog) - [Events and webinars](https://www.redhat.com/en/events) - [Podcasts and video series](https://www.redhat.com/en/red-hat-original-series) - [Red Hat TV](https://tv.redhat.com/) - [Resource library](https://www.redhat.com/en/resources) ### [For developers](https://developers.redhat.com/) Discover resources and tools to help you build, deliver, and manage cloud-native applications and services. Partners - ### For customers - [Our partners](https://www.redhat.com/en/partners) - [Red Hat Ecosystem Catalog](https://catalog.redhat.com/) - [Find a partner](https://catalog.redhat.com/partners) - ### For partners - [Partner Connect](https://connect.redhat.com/) - [Become a partner](https://connect.redhat.com/en/benefits-of-being-a-partner) - [Training](https://connect.redhat.com/en/training) - [Support](https://connect.redhat.com/en/support) - [Access the partner portal](https://connect.redhat.com/partner-admin/dashboard) ### [Build solutions powered by trusted partners](https://catalog.redhat.com/en/solutions) Find solutions from our collaborative community of experts and technologies in the Red Hat® Ecosystem Catalog. Search ### I'd like to: - [Start a trial](https://www.redhat.com/en/products/trials) - [Buy a learning subscription](https://www.redhat.com/en/services/training/learning-subscription/how-to-buy) - [Manage subscriptions](https://access.redhat.com/management) - [Contact sales](https://www.redhat.com/en/contact) - [Contact customer service](https://www.redhat.com/en/contact/customer-service) - [See Red Hat jobs](https://www.redhat.com/en/jobs) ### Help me find: - [Documentation](https://docs.redhat.com/en) - [Developer resources](https://developers.redhat.com/) - [Tech topics](https://www.redhat.com/en/topics) - [Architecture center](https://www.redhat.com/architect/portfolio/) - [Security updates](https://access.redhat.com/security/security-updates/cve) - [Customer support](https://access.redhat.com/support) ### I want to learn more about: - [AI](https://www.redhat.com/en/topics/ai) - [Application modernization](https://www.redhat.com/en/topics/application-modernization) - [Automation](https://www.redhat.com/en/topics/automation) - [Cloud-native applications](https://www.redhat.com/en/topics/cloud-native-apps) - [Linux](https://www.redhat.com/en/topics/linux) - [Virtualization](https://www.redhat.com/en/topics/virtualization) [Console](https://www.redhat.com/en/hybrid-cloud-console) [Docs](https://docs.redhat.com/en) [Support](https://access.redhat.com/) New For you ### Recommended We'll recommend resources you may like as you browse. Try these suggestions for now. - [Product trial center](https://www.redhat.com/en/products/trials) - [Courses and exams](https://www.redhat.com/en/services/training/all-courses-exams) - [All products](https://www.redhat.com/en/technologies/all-products) - [Tech topics](https://www.redhat.com/en/topics) - [Resource library](https://www.redhat.com/en/resources) Log in ### Get more with a Red Hat account - Console access - Event registration - Training & trials - World-class support A subscription may be required for some services. [Log in or register](https://sso.redhat.com/) Change page language [Contact us](https://www.redhat.com/en/contact) ### \[\[name\]\] [Edit avatar](https://access.redhat.com/user/edit) Login: \[\[login\]\] Account number: \[\[account\_number\]\] \[\[email\]\] Change page language Log out [Red Hat Blog](https://www.redhat.com/en/blog) - [By product]() - [Red Hat AI](https://www.redhat.com/en/blog/channel/red-hat-ai "Red Hat AI") - [Red Hat Ansible Automation Platform](https://www.redhat.com/en/blog/channel/red-hat-ansible-automation "Red Hat Ansible Automation Platform") - [Red Hat Enterprise Linux](https://www.redhat.com/en/blog/channel/red-hat-enterprise-linux "Red Hat Enterprise Linux") - [Red Hat OpenShift](https://www.redhat.com/en/blog/channel/red-hat-openshift "Red Hat OpenShift") *** [More products](https://www.redhat.com/en/blog/products "More products") - [By topic]() - [AI](https://www.redhat.com/en/blog/channel/artificial-intelligence "AI") - [Virtualization](https://www.redhat.com/en/blog/channel/red-hat-virtualization "Virtualization") - [Digital sovereignty](https://www.redhat.com/en/blog/channel/digital-sovereignty "Digital sovereignty") - [Applications](https://www.redhat.com/en/blog/channel/applications "Applications") - [Automation](https://www.redhat.com/en/blog/channel/management-and-automation "Automation") - [Cloud services](https://www.redhat.com/en/blog/channel/cloud-services "Cloud services") - [Edge computing](https://www.redhat.com/en/blog/channel/edge-computing "Edge computing") - [Infrastructure](https://www.redhat.com/en/blog/channel/infrastructure "Infrastructure") - [Open hybrid cloud](https://www.redhat.com/en/blog/channel/hybrid-cloud-infrastructure "Open hybrid cloud") - [Original shows](https://www.redhat.com/en/red-hat-original-series "Original shows") - [Security](https://www.redhat.com/en/blog/channel/security "Security") *** [All topics](https://www.redhat.com/en/blog/channels "All topics") - [Podcasts]() - [Technically Speaking with Chris Wright](https://www.redhat.com/en/technically-speaking "Technically Speaking with Chris Wright") - [Code Comments](https://www.redhat.com/en/code-comments-podcast "Code Comments") - [Command Line Heroes](https://www.redhat.com/en/command-line-heroes "Command Line Heroes") - [Compiler](https://www.redhat.com/en/compiler-podcast "Compiler") - [More blogs]() - [Red Hat Developer blog](https://developers.redhat.com/blog "Red Hat Developer blog") - [Red Hat Partner Connect blog](https://connect.redhat.com/en/blog "Red Hat Partner Connect blog") # Linux scripting: 3 how-tos for while loops in Bash March 11, 2021[Roberto Nozaki](https://www.redhat.com/en/authors/roberto-nozaki "See more by Roberto Nozaki")*3*\-minute read [Linux](https://www.redhat.com/en/blog?f[0]=taxonomy_topic_tid:27061#rhdc-search-listing) [Automation and management](https://www.redhat.com/en/blog?f[0]=taxonomy_topic_tid:27011#rhdc-search-listing) Share Subscribe to RSS - [Back to all posts](https://www.redhat.com/en/blog) *** Shell scripting, specifically Bash scripting, is a great way to automate repetitive or tedious tasks on your systems. Why type when you can schedule and run scripts in a hands-free manner? One of the many scripting constructs is the loop. A loop is a section of code that picks up data or generates data and then performs some operation on the data and then begins the process over again until some condition is met, the script is disrupted, or when input data is exhausted. When you use [Bash scripting](https://www.redhat.com/sysadmin/using-bash-automation), sometimes it is useful to perform actions using some form of loops. ***\[ Readers also liked: [Five ways to use redirect operators in bash](https://www.redhat.com/sysadmin/redirect-operators-bash) \]*** The basic loop commands in Bash scripts are `for` and `while`. - `for` loops are typically used when you have a known, finite list, like a series of numbers, a list of items, or counters. - `while` loops can be used with lists but are also useful for conditions that do *not* have a known limit. You can use it to run commands *while* a condition is true (or invert the logic and run it while the condition is false). So, while (pun intended) there are different ways to perform loops, in this article, I focus on examples using `while` loops. ## 1\. A simple while loop Imagine that you're installing a huge application, and you're concerned that it may eventually use too much space on the file system. Instead of running `df` in a separate terminal, you can run a simple command to monitor the disk utilization every second. This allows you to interrupt the installation process if you see that it will hit that limit. ``` while true do   df -k | grep home   sleep 1 done ``` In this case, you're running the loop with a **true** condition, which means it will run forever or until you hit **CTRL-C.** Therefore, you need to keep an eye on it (otherwise, it will remain using the system's resources). **Note**: If you use a loop like this, you need to include a command like `sleep` to give the system some time to breathe between executions. Running anything non-stop could become a performance issue, especially if the commands inside the loop involve I/O operations. ## 2\. Waiting for a condition to become true There are variations of this scenario. For example, you know that at some point, the process will create a directory, and you are just waiting for that moment to perform other validations. You can have a `while` loop to keep checking for that directory's existence and only write a message while the directory does not exist. If you want to do something more elaborate, you could create a script and show a more clear indication that the loop condition became true: ``` #!/bin/bash while [ ! -d directory_expected ] do    echo "`date` - Still waiting"     sleep 1 done echo "DIRECTORY IS THERE!!!" ``` ## 3\. Using a while loop to manipulate a file Another useful application of a `while` loop is to combine it with the `read` command to have access to columns (or fields) quickly from a text file and perform some actions on them. In the following example, you are simply picking the columns from a text file with a predictable format and printing the values that you want to use to populate an `/etc/hosts` file. Here the assumption is that the file has columns delimited by spaces or tabs and that there are *no* spaces in the content of the columns. That could shift the content of the fields and not give you what you needed. Notice that you're just doing a simple operation to extract and manipulate information and not concerned about the command's reusability. I would classify this as one of those "quick and dirty tricks." Of course, if this was something that you would repeatedly do, you should run it from a script, use proper names for the variables, and all those good practices (including transforming the filename in an argument and defining where to send the output, but today, the topic is `while` loops). ``` #!/bin/bash cat servers.txt | grep -v CPU | while read servername cpu ram ip do    echo $ip $servername done ``` ***\[ Learn the basics of using Kubernetes in this [free cheat sheet](https://developers.redhat.com/promotions/kubernetes-cheatsheet?intcmp=701f20000012ngPAAQ). \]*** ## Wrap up `while` loops are useful in scripts that depend on a certain condition to be true or false, but you can also use them interactively to monitor some condition. The important things to remember are: Always be clear about what is the condition to *end* the loop. If that is something that you expect to do yourself with a **CTRL-C**, then keep an eye on your command. Think about *how fast* you want each loop cycle to be repeated. If you do any operation that involves I/O inside the loop, that becomes a critical aspect of planning. With that in mind, have fun `while` you can. *** ### About the author [![Roberto Nozaki](https://www.redhat.com/rhdc/managed-files/styles/media_thumbnail/private/sysadmin/pictures/2022-11/RoberoNozaki.jpeg?itok=WBbw9DVe)](https://www.redhat.com/en/authors/roberto-nozaki) [Roberto Nozaki](https://www.redhat.com/en/authors/roberto-nozaki) Roberto Nozaki (RHCSA/RHCE/RHCA) is an Automation Principal Consultant at Red Hat Canada where he specializes in IT automation with Ansible. He has experience in the financial, retail, and telecommunications sectors, having performed different roles in his career, from programming in mainframe environments to delivering IBM/Tivoli and Netcool products as a pre-sales and post-sales consultant. Roberto has been a computer and software programming enthusiast for over 35 years. He is currently interested in hacking what he considers to be the ultimate hardware and software: our bodies and our minds. Roberto lives in Toronto, and when he is not studying and working with Linux and Ansible, he likes to meditate, play the electric guitar, and research neuroscience, altered states of consciousness, biohacking, and spirituality. [Read full bio](https://www.redhat.com/en/authors/roberto-nozaki) ## More like this Blog post ### [Enable intelligent insights with Red Hat Satellite MCP Server](https://www.redhat.com/en/blog/enable-intelligent-insights-red-hat-satellite-mcp-server) Blog post ### [Strategic momentum: The new era of Red Hat and HPE Juniper network automation](https://www.redhat.com/en/blog/strategic-momentum-new-era-red-hat-and-hpe-juniper-network-automation) Original podcast ### [Technically Speaking \| Taming AI agents with observability](https://www.redhat.com/en/technically-speaking/taming-ai-agents-observability) Original podcast ### [You Can’t Automate Expectations \| Code Comments](https://www.redhat.com/en/code-comments-podcast/season-2/cox-edge) ## Browse by channel [Explore all channels](https://www.redhat.com/en/blog/channels "Explore all channels") ![automation icon](https://www.redhat.com/cms/managed-files/automation.svg) ### [Automation](https://www.redhat.com/en/blog/channel/management-and-automation) The latest on IT automation for tech, teams, and environments ![AI icon](https://www.redhat.com/cms/managed-files/AI.svg) ### [Artificial intelligence](https://www.redhat.com/en/blog/channel/artificial-intelligence) Updates on the platforms that free customers to run AI workloads anywhere ![open hybrid cloud icon](https://www.redhat.com/cms/managed-files/open-hybrid-cloud.svg) ### [Open hybrid cloud](https://www.redhat.com/en/blog/channel/hybrid-cloud-infrastructure) Explore how we build a more flexible future with hybrid cloud ![security icon](https://www.redhat.com/cms/managed-files/security.svg) ### [Security](https://www.redhat.com/en/blog/channel/security) The latest on how we reduce risks across environments and technologies ![edge icon](https://www.redhat.com/cms/managed-files/edge_2.svg) ### [Edge computing](https://www.redhat.com/en/blog/channel/edge-computing) Updates on the platforms that simplify operations at the edge ![Infrastructure icon](https://www.redhat.com/cms/managed-files/infrastructure.svg) ### [Infrastructure](https://www.redhat.com/en/blog/channel/infrastructure) The latest on the world’s leading enterprise Linux platform ![application development icon](https://www.redhat.com/cms/managed-files/application-development.svg) ### [Applications](https://www.redhat.com/en/blog/channel/applications) Inside our solutions to the toughest application challenges ![Virtualization icon](https://www.redhat.com/rhdc/managed-files/Icon-Red_Hat-Virtual_server-A-Black-RGB.svg) ### [Virtualization](https://www.redhat.com/en/blog/channel/red-hat-virtualization) The future of enterprise virtualization for your workloads on-premise or across clouds [![Red Hat logo](https://static.redhat.com/libs/redhat/brand-assets/2/corp/logo--on-dark.svg)](https://www.redhat.com/en) [LinkedIn](https://www.linkedin.com/company/red-hat) [YouTube](https://www.youtube.com/user/RedHatVideos) [Facebook](https://www.facebook.com/RedHat/) [X](https://twitter.com/RedHat) ### Platforms - [Red Hat AI](https://www.redhat.com/en/products/ai) - [Red Hat Enterprise Linux](https://www.redhat.com/en/technologies/linux-platforms/enterprise-linux) - [Red Hat OpenShift](https://www.redhat.com/en/technologies/cloud-computing/openshift) - [Red Hat Ansible Automation Platform](https://www.redhat.com/en/technologies/management/ansible) - [See all products](https://www.redhat.com/en/technologies/all-products) ### Tools - [Training and certification](https://www.redhat.com/en/services/training-and-certification) - [My account](https://www.redhat.com/wapps/ugc/protected/personalInfo.html) - [Customer support](https://access.redhat.com/) - [Developer resources](https://developers.redhat.com/) - [Find a partner](https://catalog.redhat.com/partners) - [Red Hat Ecosystem Catalog](https://catalog.redhat.com/) - [Documentation](https://docs.redhat.com/en) ### Try, buy, & sell - [Product trial center](https://www.redhat.com/en/products/trials) - [Red Hat Store](https://www.redhat.com/en/store) - [Buy online (Japan)](https://www.redhat.com/en/about/japan-buy) - [Console](https://www.redhat.com/en/hybrid-cloud-console) ### Communicate - [Contact sales](https://www.redhat.com/en/contact/sales) - [Contact customer service](https://www.redhat.com/en/contact/customer-service) - [Contact training](https://www.redhat.com/en/services/training-and-certification/contact-us) - [Social](https://www.redhat.com/en/about/social) ### About Red Hat Red Hat is an open hybrid cloud technology leader, delivering a consistent, comprehensive foundation for transformative IT and artificial intelligence (AI) applications in the enterprise. As a [trusted adviser to the Fortune 500](https://www.redhat.com/en/about/company), Red Hat offers cloud, developer, Linux, automation, and application platform technologies, as well as [award-winning](https://access.redhat.com/recognition) services. - [Our company](https://www.redhat.com/en/about/company) - [How we work](https://www.redhat.com/en/about/our-culture) - [Customer success stories](https://www.redhat.com/en/success-stories) - [Analyst relations](https://www.redhat.com/en/about/analysts) - [Newsroom](https://www.redhat.com/en/about/newsroom) - [Open source commitments](https://www.redhat.com/en/about/open-source) - [Our social impact](https://www.redhat.com/en/about/community-social-responsibility) - [Jobs](https://www.redhat.com/en/jobs) ### Change page language ### Red Hat legal and privacy links - [About Red Hat](https://www.redhat.com/en/about/company) - [Jobs](https://www.redhat.com/en/jobs) - [Events](https://www.redhat.com/en/events) - [Locations](https://www.redhat.com/en/about/office-locations) - [Contact Red Hat](https://www.redhat.com/en/contact) - [Red Hat Blog](https://www.redhat.com/en/blog) - [Inclusion at Red Hat](https://www.redhat.com/en/about/our-culture/inclusion) - [Cool Stuff Store](https://coolstuff.redhat.com/) - [Red Hat Summit](https://www.redhat.com/en/summit) © 2026 Red Hat ### Red Hat legal and privacy links - [Privacy statement](https://www.redhat.com/en/about/privacy-policy) - [Terms of use](https://www.redhat.com/en/about/terms-use) - [All policies and guidelines](https://www.redhat.com/en/about/all-policies-guidelines) - [Digital accessibility](https://www.redhat.com/en/about/digital-accessibility)
Readable Markdown
Shell scripting, specifically Bash scripting, is a great way to automate repetitive or tedious tasks on your systems. Why type when you can schedule and run scripts in a hands-free manner? One of the many scripting constructs is the loop. A loop is a section of code that picks up data or generates data and then performs some operation on the data and then begins the process over again until some condition is met, the script is disrupted, or when input data is exhausted. When you use [Bash scripting](https://www.redhat.com/sysadmin/using-bash-automation), sometimes it is useful to perform actions using some form of loops. ***\[ Readers also liked: [Five ways to use redirect operators in bash](https://www.redhat.com/sysadmin/redirect-operators-bash) \]*** The basic loop commands in Bash scripts are `for` and `while`. - `for` loops are typically used when you have a known, finite list, like a series of numbers, a list of items, or counters. - `while` loops can be used with lists but are also useful for conditions that do *not* have a known limit. You can use it to run commands *while* a condition is true (or invert the logic and run it while the condition is false). So, while (pun intended) there are different ways to perform loops, in this article, I focus on examples using `while` loops. ## 1\. A simple while loop Imagine that you're installing a huge application, and you're concerned that it may eventually use too much space on the file system. Instead of running `df` in a separate terminal, you can run a simple command to monitor the disk utilization every second. This allows you to interrupt the installation process if you see that it will hit that limit. ``` while true do   df -k | grep home   sleep 1 done ``` In this case, you're running the loop with a **true** condition, which means it will run forever or until you hit **CTRL-C.** Therefore, you need to keep an eye on it (otherwise, it will remain using the system's resources). **Note**: If you use a loop like this, you need to include a command like `sleep` to give the system some time to breathe between executions. Running anything non-stop could become a performance issue, especially if the commands inside the loop involve I/O operations. ## 2\. Waiting for a condition to become true There are variations of this scenario. For example, you know that at some point, the process will create a directory, and you are just waiting for that moment to perform other validations. You can have a `while` loop to keep checking for that directory's existence and only write a message while the directory does not exist. If you want to do something more elaborate, you could create a script and show a more clear indication that the loop condition became true: ``` #!/bin/bash while [ ! -d directory_expected ] do    echo "`date` - Still waiting"     sleep 1 done echo "DIRECTORY IS THERE!!!" ``` ## 3\. Using a while loop to manipulate a file Another useful application of a `while` loop is to combine it with the `read` command to have access to columns (or fields) quickly from a text file and perform some actions on them. In the following example, you are simply picking the columns from a text file with a predictable format and printing the values that you want to use to populate an `/etc/hosts` file. Here the assumption is that the file has columns delimited by spaces or tabs and that there are *no* spaces in the content of the columns. That could shift the content of the fields and not give you what you needed. Notice that you're just doing a simple operation to extract and manipulate information and not concerned about the command's reusability. I would classify this as one of those "quick and dirty tricks." Of course, if this was something that you would repeatedly do, you should run it from a script, use proper names for the variables, and all those good practices (including transforming the filename in an argument and defining where to send the output, but today, the topic is `while` loops). ``` #!/bin/bash cat servers.txt | grep -v CPU | while read servername cpu ram ip do    echo $ip $servername done ``` ***\[ Learn the basics of using Kubernetes in this [free cheat sheet](https://developers.redhat.com/promotions/kubernetes-cheatsheet?intcmp=701f20000012ngPAAQ). \]*** ## Wrap up `while` loops are useful in scripts that depend on a certain condition to be true or false, but you can also use them interactively to monitor some condition. The important things to remember are: Always be clear about what is the condition to *end* the loop. If that is something that you expect to do yourself with a **CTRL-C**, then keep an eye on your command. Think about *how fast* you want each loop cycle to be repeated. If you do any operation that involves I/O inside the loop, that becomes a critical aspect of planning. With that in mind, have fun `while` you can.
Shard14 (laksa)
Root Hash4780968593380432814
Unparsed URLcom,redhat!www,/en/blog/bash-scripting-while-loops s443