Skip to main content
25 votes
Accepted

How do bash loops work precisely?

Ordinary for loops always iterate over a static set of strings. This is regardless of whether the strings are generated by brace expansions or by filename globbing patterns, or some other expansion of ...
Kusalananda's user avatar
  • 356k
23 votes
Accepted

In for loops in bash, is the counter variable local or global?

for doesn’t introduce its own variable scope, so i is whatever it is on entry to the for loop. This could be global, or local to whatever function declared it as local, or even global but in a sub-...
Stephen Kitt's user avatar
22 votes
Accepted

How to loop for 3 times in bash script when docker push fails?

Use for-loop and && break: for n in {1..3}; do docker push $CONTAINER_IMAGE:latest && break; done break quits the loop, but only runs when docker push succeeded. If docker push ...
pLumo's user avatar
  • 23.2k
17 votes
Accepted

Looping over dirs using `find . -depth 1 -type d`

The -depth switch does not take an argument, but -maxdepth does, so: for dir in `find . -depth -maxdepth 1 -type d` do .... should work. The -depth argument as per the man page means process ...
Bob Goddard's user avatar
  • 2,751
13 votes
Accepted

Adding suffix to filename during for loop in bash

for file in TLC*.csv; do cut -d, -f2- "${file}" > "${file%.*}_prepped.csv" done ${file%.*} removes everything after the last dot of $file. If you want to remove everything ...
Quasímodo's user avatar
  • 19.4k
13 votes

Bash for loop with string var containing spaces

If you're using bash you can use an array for this #!/bin/bash files=('foo bar' 'another file' file1 'file2') for f in "${files[@]}"; do file -- "$f"; done Quoting is required for ...
Chris Davies's user avatar
13 votes
Accepted

How can I assign the output of a command to different variables in each loop iteration?

In your case, I would use an associative array for that: declare -A rules for chain in http https ssh do rules[$chain]=$(iptables -nvxL $chain | tail -1 | awk '{print $2}') done You can then ...
AdminBee's user avatar
  • 23.6k
12 votes

echo list / array to xargs

printf '%s\n' "${list[@]}" | xargs This would print each element of list on its own line and that newline-delimited list would be passed to xargs. "${list[@]}" would expand to the ...
Kusalananda's user avatar
  • 356k
12 votes
Accepted

changing IFS temporarily before a for loop

for is a reserved word and as such follows special rules: The following words shall be recognized as reserved words: ! { } case do done elif else esac fi for if in then until while This recognition ...
Quasímodo's user avatar
  • 19.4k
11 votes
Accepted

How to convert an input parameter to integer value in a for loop in bash?

You can do this two ways: With ksh93-compatible shells (ksh93, zsh, bash): for (( i=1;i<=$2;i++ )) do echo "Welcome $i times" done Here we set i to 1 and loop, incrementing it until it ...
Raman Sailopal's user avatar
11 votes

bash loop to replace middle of string after a certain character

I think you were very close to a working command. This worked for me on the few examples you gave: sed -E 's/_[0-9]+ /|/' "$file" > "$file.1" I changed the match expression ...
Sotto Voce's user avatar
  • 7,221
10 votes

for loop not working in bash

The $(foo) construct will run the command foo and replace $(foo) with the output of running foo. You want a glob, that's not a command. What you're doing is attempting to run all files called ./zebu....
terdon's user avatar
  • 252k
10 votes
Accepted

How to run a loop inside sh -c

The usual wisdom is to define the script (after the -c) inside single quotes. The other part you need to use is a shell where the {1..4} construct is valid: $ bash -c 'for i in {1..4}; do echo $i; ...
QuartzCristal's user avatar
9 votes
Accepted

Why does bash replaces text from command substitution with text thereafter

The problem is that your files have DOS/Windows-style line-endings. As a quick work-around, replace: echo "$(cat "$enabled") |" With: echo "$(tr -d '\r' <"$enabled") |" Here, tr removes the ...
John1024's user avatar
  • 76.4k
9 votes
Accepted

Weird bash behavior when IFS is set for a for loop

Keywords aren't recognized after an assignment. So, the for in IFS=blah for ... just runs a regular command called for, if you have one: $ cat > ./for #!/bin/sh echo script for $ chmod +x ./for $...
ilkkachu's user avatar
  • 148k
9 votes

loop through one file extension or the other in bash or zsh

You don't. You iterate over both "extensions" and (if you need to) check if either or both exist. e.g. if you only want to print one or the other (the first one seen), keep a list of the ...
cas's user avatar
  • 84.4k
8 votes
Accepted

Bash: Multiple for loops in Background

The outer loop that you have is basically for i in {1..10}; do some_compound_command & done This would start ten concurrent instances of some_compound_command in the background. They will be ...
Kusalananda's user avatar
  • 356k
8 votes
Accepted

Bash script - variables in curly braces

Variables won't expand inside brace expansion. You could do: for ((number=startNumber; number<=endNumber; number++)); do echo "$number" done Also, there is no reason to use ...
jesse_b's user avatar
  • 41.6k
8 votes

Bash script - variables in curly braces

As explained elsewhere the expansion won't work. Alternative way to get your sequence of numbers: for number in $(seq $startNumber $endNumber) do echo $number done
bxm's user avatar
  • 5,210
8 votes
Accepted

Loop through MAC addresses, how to handle both numbers (0-9) and letters (a-f) in a "for" loop

Just add another brace expansion for the letters: for i in {2..9} {a..f} do grep "Node${i}\|01, source address = 00:00:00:00:00:0${i}" t1.txt > t2.txt done Note that this is likely ...
terdon's user avatar
  • 252k
7 votes
Accepted

Rename files using a WHILE loop instead of a FOR loop

There's nothing wrong with using a while loop here. You just have to do it right: set -- *.jpeg while (($#)); do mv -- "${1}" "${1/DSC/Paris}" shift done The while loop above is just as reliable as ...
don_crissti's user avatar
  • 85.7k
7 votes

Loop to create subdirectories in multiple directories

Assuming the m3* directories exist, for dir in m3z m3t m3t2 m3g m3g2 m3g3; do mkdir "$dir"/{log,lib,txt} done or, with brace expansion on the list of directories, mkdir {m3z,m3t,m3t2,m3g,m3g2,...
Kusalananda's user avatar
  • 356k
7 votes
Accepted

Inner for loop when run in background in bash spawns new bash process

Because you have piped the loop into grep, it must be run in a subshell. This is mentioned in the Bash manual: Each command in a pipeline is executed in its own subshell, which is a separate process ...
Michael Homer's user avatar
7 votes

Run script for 10 times or until it meets the condition

The break builtin is used for this. for i in {1..10}; do sleep 10 OUTPUT=$(systemctl is-active etcd) if [[ $OUTPUT == active ]]; then echo "The result is successful" break ...
jesse_b's user avatar
  • 41.6k
7 votes
Accepted

How to watch a for-loop in bash?

watch's command argument(s) are a script that is run with sh -c. If the command arguments are just a list of tokens separated by spaces (e.g. watch ls -l), it concatenates them all and runs them. ...
cas's user avatar
  • 84.4k
7 votes

For loop through a variable vector

In Bash and ksh, referencing an array without an index ($foo) is the same as referencing it with an index of 0 (${foo[0]}). The way to get all elements of the array is to index with the special value @...
ilkkachu's user avatar
  • 148k
6 votes
Accepted

Using a For Loop to Sort and Save Files Using Grep

(in adition to @Philippos): Bash is trying to expand variable $i_ instead of $i. Try ...${i}_...: for i in {00..21} do grep "text" file_${i}_*out > out_$i.txt done
JJoao's user avatar
  • 12.8k
6 votes

how can we use multiple variables in single for loop in shell script?

$ cat inputfile.txt foo|bar baz|foobar $ cat inputfile.txt | while IFS='|' read i j ; do echo $i:$j ; done foo:bar baz:foobar this answer is a lot like this answer but it also answers the comment ...
Jonas Maanmies's user avatar
6 votes

How do I get 0-padded numbers in {} (brace expansion)?

Although Brace expansion has a zero-padding method, I found Parameter expansion more useful to alter existing variable: digits=00000 num=123 # Option 1: temp=$digits$num echo ${temp:(-${#digits})} # ...
Noam Manos's user avatar
  • 1,129
6 votes

Force alphabetical order in for loop with if conditions

#/bin/sh # shellcheck disable=SC2046 # ^ word-splitting by the shell is intentional in this file elems="Cr Hf Mo Nb Ta Ti V W Zr" for a in $elems do for b in $elems do for c in $...
n.st's user avatar
  • 8,418

Only top scored, non community-wiki answers of a minimum length are eligible