- How to write a single line shell script with a while loop and if statement
- 3 Answers 3
- Create One Line Loop in Bash
- Create One Line Loop in Linux Bash
- Write Each Element Inside the Loop
- Specify a Range of Numbers
- Create Loop With Subcommand
- Related Article — Bash Loop
- Bash While Loop on One Line
- Example 01:
- Example 02:
- Example 03:
- Conclusion:
- About the author
- Omar Farooq
- Bash for Loop in One Line
- Bash for loop
- For loop structure
- One line for loop
- For loop with conditionals
- Miscellaneous examples
- Final thought
- About the author
- Sidratul Muntaha
How to write a single line shell script with a while loop and if statement
I am trying to figure out the syntax for having a while loop and an if statement that checks for more than one condition, in a single-line shell script. Executing something like this.
i=2; while [ $i -le 10 ]; do if [ $i -ne 3 -a $i -ne 5 ] echo $i " not equal to 3 or 5"; else echo $i; i=`expr $i + 1`; done
bash: syntax error near unexpected token `else'
On another hand if I remove the semicolon from between . 3 or 5″ and else echo. , and try something like this.
i=2; while [ $i -le 10 ]; do if [ $i -ne 3 -a $i -ne 5 ] echo $i " not equal to 3 or 5" else echo $i; i=`expr $i + 1`; done
syntax error near unexpected token `done'
This is on an Ubuntu 14.04, in case it matters. Am I perhaps missing some kind of a parenthesis somewhere, or is it something else?
The basic idea is to simply use the end-of-line delimiter ‘;’ wherever you would normally have a newline if you had written the script as a normally-formatted multi-line script. As noted below, you have missing then and fi ‘s as well.
3 Answers 3
i=2; while [ $i -le 10 ]; do if [ $i -ne 3 -a $i -ne 5 ]; then echo $i " not equal to 3 or 5"; else echo $i; fi; i=`expr $i + 1`; done
and this should also work:
i=2; while [ $i -le 10 ]; do [ $i -ne 3 -a $i -ne 5 ] && echo "$i not equal to 3 or 5" || echo $i; i=$((i+1)); done
But I am not sure if it makes sense to write this in only one line
You still need a then , and a fi , and enough semicolons.
i=2; while [ $i -le 10 ]; do if [ $i -ne 3 -a $i -ne 5 ]; then echo "$i not equal to 3 or 5"; else echo $i; fi; i=$(expr $i + 1); done
The replacement of back-quotes `…` with $(…) is just a general good idea, not crucial to this discussion.
If written out conventionally on multiple lines (without semicolons), you’d have:
i=2 while [ $i -le 10 ] do if [ $i -ne 3 -a $i -ne 5 ] then echo "$i not equal to 3 or 5" else echo $i fi i=$(expr $i + 1) done
To convert that to a single line, you need a semicolon after each statement and condition:
i=2; while [ $i -le 10 ]; do if [ $i -ne 3 -a $i -ne 5 ]; then echo "$i not equal to 3 or 5"; else echo $i; fi; i=$(expr $i + 1); done
And now the white space (including newlines) can be replaced by single spaces on a single line.
And you could use i=$(($i + 1)) or even (in Bash) ((i++)) in place of expr , which avoids the use of the external command expr ; the shell does the arithmetic internally.
I don’t think there is a good reason to flatten the script onto one line.
Create One Line Loop in Bash
This article will explain how we can create one-line loops in Linux Bash. We will write example scripts with the for loop.
Create One Line Loop in Linux Bash
We can create simple one-line loops in different ways as follows.
Write Each Element Inside the Loop
We can write the elements in the loop one by one.
for i in "apple" "banana" "orange"; do echo "$i"; done
Specify a Range of Numbers
A range of numbers can be used to create a one-line loop.
for i in 1..3>; do echo "step: $i"; done
Create Loop With Subcommand
We can use subcommands to specify the values used in the loop. This method is especially useful for reading file contents.
for i in `seq 1 3`; do echo "step: $i"; done;
for i in `cat file.txt`; do echo "step: $i"; done;
Yahya Irmak has experience in full stack technologies such as Java, Spring Boot, JavaScript, CSS, HTML.
Related Article — Bash Loop
Bash While Loop on One Line
Like many other programming languages, Bash programming also supports the use of “loops” in its code. There are a lot of loops supported by Bash coding, i.e., for loop and while loop. You may have used both the “for” and “while” loop in your programs while coding. But have you ever tried to use the loop on a single line with all its working? If not! Then, this article is meant for you and all the Linux users who want to try the “while” loop in a single line of Bash code.
Today, we will be discussing some of the simple and easy-to-understand examples in our article. Let’s start with the Ubuntu 20.04 Linux terminal shell application launch using the “Ctrl+Alt+T” shortcut.
Example 01:
Now, the terminal application has been launched. It’s time to create a new Bash file. For this, you need to utilize the simple “touch” query of Bash programming to create a new Bash file containing the Bash extension, i.e., “bash.sh”. The file has been generated within Ubuntu’s home folder. You have to open it within some editor to start adding Bash script. To open a file and add code, we have been utilizing the GNU Nano editor. For that, try using the keyword “nano” with the file name on the instruction area of the terminal and execute it. The file will open as an empty screen.
Let’s start with the first example of using the “while” loop on one line of the Bash code. As the file is empty, we need to add the Bash extension in our Bash file to make it execute as a “Bash” script. It is not essential to add the extension. Your code will execute perfectly fine without using the Bash support in the file if you have named it with the “.sh” extension or run it with the keyword “bash”. As we have to use the one-line “while” loop in the code, we are fulfilling our promise here. The while loop started with the keyword “true” states that the loop will continue to execute until “true”, i.e., it will not stop its execution until the user ends the program itself.
Within its “do” part, we have added the “echo” statement to print the string “hello” on the shell. The “while” loop on one-line ends at the “done” keyword. Let’s save your code and exit to execute it now.
Let’s run our file with the Bash command, i.e., using the “bash” keyword as shown below.
Upon execution, the program has started to output the string “hello” without stopping as per the following output. If you want to exit this one-line loop, press “Ctrl+X” on the shell. Now, check out the output in the following screenshot:
Example 02:
Let’s look at another one-line “while” loop used in the Bash code. This code will be similar to the previous example code but with a slight change. So, we open the same Bash file and update the code. We have been using the same “while true” statement to start the continuous loop without end. Within its “do” part, we use the “echo” statement to display a message that our system will have a 3-second sleep on every message display. The “sleep” function has been used within the “do” part of the one-line while loop to take a 3-second sleep on every display of string message by the “echo” clause. Thus, the loop will be ended at the “done” part.
The program for the one-line while loop is complete and ready to get executed. Save it with the “ctrl+S” and exit the file with the “Ctrl+X” shortcut.
After the file exit, we have executed it with the “Bash” instruction. The program code started to display the string “Hello, sleeping for 3 seconds” with the pause of 3 seconds after every message displayed on the shell as presented below:
The one-line “while” loop will continue to execute this program until we quit it forcefully. As a result, we need to use the “Ctrl+Z” shortcut to halt its execution temporarily. Now, check out the output in the following screenshot:
Example 03:
If you don’t want your one-line loop to continue its execution without any stop, you can do that. So, we have decided to create one example for such a type of one-line while loop. Thus, I started the Bash file within the nano editor and added the Bash support at the first line. After that, we have initialized an integer value “i” with 2. At the following line, we use the “while” loop to iterate itself until its specified condition is satisfied. The condition says that the value of a variable “i” must be less than or equal to “14” via the “-le” operator of Bash. If so, the loop will execute its “do” part, and the “echo” statement will display the current iteration value. On execution of the “do” part, the value of “I” will be incremented by 3. The loop ends here, and we have to run the following Bash code now:
On every iteration, the system continues to display the iteration value and increments it by 3 until it reaches the value “14”. Now, check out the output in the following screenshot:
Conclusion:
This article has thoroughly explained all the Bash examples using the one-line while loop with different conditions. We have discussed the non-ending one-line loop and the conditional loop that can end on its own. Thus, we can say that our article contains quite diverse examples for our Linux users. All of the previous examples can be amended as per the needed work. We hope you found this article helpful. Check the other Linux Hint articles for more tips and tutorials.
About the author
Omar Farooq
Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.
Bash for Loop in One Line
In any programming or scripting language, the loop is a quintessential feature. Loops are generally to perform a repetitive task until a certain condition is met. Bash is a powerful scripting language that supports all the major features of a scripting language (including loops).
This guide demonstrates one-line for loops in Bash.
Bash for loop
The bash features multiple loop types – for, while, and until. Each type of loop comes with a different structure. However, the fundamentals remain the same. For beginners, this guide explains in-depth about various bash loops and how to implement them.
As the title of this guide suggests, our focus will be on the loop. While for loop generally requires multiple lines, we can represent it in a single line if the loop is simple enough. This process, however, requires an understanding of the fundamentals of bash for a loop.
To run our bash codes, we need a shell script. I already have a dummy script to run our codes.
For loop structure
This is the basic structure of the bash for loop.
Here’s a quick for loop example implementing this structure.
Bash also supports C-style for loop. If you have programming background in C, then C-style for loop will be easy to understand.
Let’s put the C-style for loop in action.
For loop can also work with files. In the following example, the loop will search all the partitions under the disk “/dev/sda” and print all of it.
One line for loop
With the basics covered, we can now compress for loops into a single line. Basically, we’ll eliminate the newlines from the entire for loop code. We can also run these loops directly from the command line.
Let’s compress the first example. If we eliminate all the new lines, the code will look like this.
As you can see, all the new lines are removed. Instead, those newlines are replaced with semicolons (;).
We can do the same with C-style for loops.
Have a look at the following example. All the configuration files inside “/etc.” will be copied as a backup to the “~/backup” directory.
For loop with conditionals
In many cases, a loop will contain conditionals to make decisions at various points of the repetition.
Here, the following for loop will print all the even numbers within a fixed range.
It’s possible to express this entire loop into a single line. Just like before, replace all the newline with semicolons (;).
It’s recommended to write down the loop with proper spacing first. Once the loop is confirmed to work properly, we can safely compress it into a single line.
Miscellaneous examples
Here’s a handful of one line for loops for reference.
The next example will be of an infinite loop.
Final thought
This guide demonstrates various effective one-line for loop examples. It’s very easy to transform a normal for loop into one line. Hopefully, after practicing these examples, readers will have a good idea of using bash for loop in one line.
About the author
Sidratul Muntaha
Student of CSE. I love Linux and playing with tech and gadgets. I use both Ubuntu and Linux Mint.