You can use for loop to iterate the values of an array. Create a new bash file named loop2.sh with the following script. In this example, the loop retrieves the values from an array variable named ColorList, and it will print the output only if the Pink value is found in the array...
forloop1.sh #!/bin/bash echo "Enter a text of multiple words" read text i=1 for word in $text do echo "Word No-$i = $word" ((i=$i+1)) done Output: Run the script. $ bash forloop1.sh Here, a text of 5 words is taken, so five lines of output are printed. Example-2...
Example 4: Using Command Substitution #!/bin/zshforuserin$(cut-d:-f1/etc/passwd)doecho"User:$user"done for user in $(cut -d: -f1 /etc/passwd): The loop iterates over all usernames in the /etc/passwd file. Example 5: C-style for Loop ...
A 'for loop' is a bash programming language statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement i.e. it is the repetition of a process within a bash script. Tutorial details For example, you can run UNIX command or task 5 times or ...
Example 4 : For loop Using Command Substitution to Specify Arguments The syntax for command substitution in a Bash shell is: for var in `cmd_sub` The following example uses the output of the cat command as the argument list. $ cat fruit1 ...
The range syntax also works for letters. For example: #!/bin/bash # For loop with letter range for i in {a..f} do echo "Element $i" done The script outputs letters to the console in ascending order in the provided range. The range syntax works for elements in descending order if ...
for loop example Now after running the abovefor loopcommand press the up arrow key from the terminal and you can see the multi-linefor loopis converted to a single line for a loop. Example 2 - Working with ranges You may want to run thefor loopNnumber of times, for that, you can ...
Now let's look at standard Bash for Loop over Strings. For instance, in the below example, the loop will repeat each item in the list of strings and variable element fixed to the current item. for element in Gold Silver Diamond Platinum do echo "Element: $element" Done Over a Number ...
Then we need to run below bash for loop fromi=1 to i<=3to convert the rows into columns. [root@localhost ~]#for ((i=1;i<=3;i++)); do cut -d, -f "$i" testfile.txt | paste -sd, ; done | column -t -s,Hi This hello you is world there CYBERITHUB example ...
this method. You should not include the keyword “in” in the for loop. If you leave the keyword “in” without any values, it will not use the positional parameter as shown below. It will not go inside the loop. i.e for loop will never get executed as shown in the example below....