> For the complete documentation index, see [llms.txt](https://cajac.gitbook.io/ctf-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cajac.gitbook.io/ctf-notes/prog/bash-scripting/looping.md).

# Looping

## For loops in bash

`for` loops with [brace expansions](https://www.gnu.org/software/bash/manual/bash.html#Brace-Expansion)

```bash
for user in {A..Z}; do echo "---$user---"; curl -A "$user" -L http://10.10.173.162; done
```

```bash
for enc in {s,S,b,l,B,L}; do strings -a -e$enc -n 8 file; done
```

`for` loop with [command substitution](https://www.gnu.org/software/bash/manual/bash.html#Command-Substitution)

```bash
for f in $(cat file_candidates.txt); do find / -type f -name $f 2>/dev/null; done >> file_candidates_full.txt
```

```bash
for num in $(seq 1 10); do curl -s -b cookie.jar http://$TARGET_IP/api/users/profile.php?id=$num | jq; done
```

Combined `for` loop example

```bash
for gem in "amethyst" "ruby" "saphire" "emerald"; for role in $(cat /tmp/role-names.txt); do echo "$gem-$role"; done  | tee /tmp/gem-roles.txt
```

## While loops in bash

An example of a while loop in bash

```bash
#!/bin/bash
PORT=59992

KEEP_GOING=true
while [ $KEEP_GOING = true ]
do
    curl -s -X 'POST' -H 'Content-Type: application/json' -H 'Content-Length: 14' --data-binary '{"circuit":[]}' "http://activist-birds.picoctf.net:$PORT/check" | grep -oE 'picoCTF{[^}]*}'
    if [ $? -eq 0 ]; then
        KEEP_GOING=false
    fi
done
```

## Resources

Brace Expansion - Bash Reference Manual: <https://www.gnu.org/software/bash/manual/bash.html#Brace-Expansion>

Command Substitution - Bash Reference Manual: <https://www.gnu.org/software/bash/manual/bash.html#Command-Substitution>

Looping Constructs - Bash Reference Manual: <https://www.gnu.org/software/bash/manual/bash.html#Looping-Constructs>

seq - Linux manual page: <https://man7.org/linux/man-pages/man1/seq.1.html>
