{"id":1869,"date":"2020-11-17T10:42:17","date_gmt":"2020-11-17T10:42:17","guid":{"rendered":"https:\/\/linuxdigest.com\/?p=1869"},"modified":"2020-12-13T17:11:17","modified_gmt":"2020-12-13T17:11:17","slug":"for-loops-in-bash","status":"publish","type":"post","link":"https:\/\/linuxdigest.com\/howto\/for-loops-in-bash\/","title":{"rendered":"For loops in bash"},"content":{"rendered":"\n
You can use for loops in bash just like in any other programing language. The basic syntax is like this:<\/p>\n\n\n\n
for variable-name in 1 2 3\ndo\n list-of-commands\ndone\n<\/code><\/pre>\n\n\n\nOne line for loop in bash<\/h2>\n\n\n\n
To do a quick one-liner with for, we use a semicolon to separate each line. In this example, we will give for a list of 4 items to iterate through.<\/p>\n\n\n\n
~$ for i in 1 2 3 4; do echo \"This is line number $i\"; done;\nThis is line number 1\nThis is line number 2\nThis is line number 3\nThis is line number 4\n<\/code><\/pre>\n\n\n\nFor loop in a bash script<\/h2>\n\n\n\n
When writing a script. We don’t need to use the semicolon as in the example above. This time we write each part of the command on a separate line. This example will print exactly the same output as the one-liner we just did.<\/p>\n\n\n\n
for i in 1 2 3 4\ndo\n echo \"This is line number $i\"\ndone<\/code><\/pre>\n\n\n\nUse a command to get a list of items<\/h2>\n\n\n\n
Instead of giving for a long list of items to iterate through, we can also wrap a command in $( ) to get the list. In this example we use the seq command to get a list of numbers 1 through 4. This will output exactly the same as above.<\/p>\n\n\n\n
for i in $( seq 1 4 )\ndo\n echo \"This is line number $i\"\ndone\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"You can use for loops in bash just like in any other programing language. The basic…<\/p>\n","protected":false},"author":1,"featured_media":1919,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[1],"tags":[],"yoast_head":"\n
For loops in bash - Linux Digest<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n\n\n\n\t\n\t\n\t\n