How can I check the length of a string in a Bash loop at a specific iteration?

0
0
Asked By CuriousCoder123 On

I'm working on a Bash script where I need to base64 encode a string multiple times, specifically checking the length of the string when the loop reaches the 35th iteration. Here's what I've got:

```bash
#! /bin/bash
var="nef892na9s1p9asn2aJs71nIsm"
for counter in {1..40}; do
var=$(echo $var | base64)
# How do I specifically check the length at counter=35?
done
```

What I'm trying to achieve is to print just the character count of **$var** exactly when the loop hits iteration 35, without any extra text or newlines. So far, I've tried various methods like `${#var}`, but I keep running into issues with it disappearing after more encodings or being affected by newlines. Any advice?

4 Answers

Answered By EchoEliminator On

Here’s a clean approach:

```bash
#! /bin/bash
var="nef892na9s1p9asn2aJs71nIsm"
for counter in {1..40}; do
var=$(printf '%s' "$var" | base64)
if [ $counter -eq 35 ]; then
printf '%d' ${#var}
fi
done
```

This avoids adding a newline every time, and you should only see the count at iteration 35.

Answered By TaskTamer On

**Key Takeaway:** Use `printf` instead of `echo` to prevent newline issues. Here’s a simple script you can run:

```bash
#! /bin/bash
var="nef892na9s1p9asn2aJs71nIsm"
for counter in {1..40}; do
var=$(printf '%s' "$var" | base64)
if [ $counter -eq 35 ]; then
echo -n ${#var}
break
fi
done
```

This will print just the character count at iteration 35 ready for you to use!

Answered By LoopGuru On

This code should work for you:

```bash
#! /usr/bin/env bash
var="nef892na9s1p9asn2aJs71nIsm"
for counter in {1..40}; do
var=$(echo $var | base64 --wrap=0)
[[ $counter == 35 ]] && echo -n ${#var}
done
```

The `--wrap=0` prevents any wrapping issues, so you should just get the number without newline characters.

Answered By Base64BashWizard On

You might want to use something like this:

```bash
for ((counter = 1; counter <= 40; counter++)); do
currentString=$(printf '%s' "$currentString" | base64 | tr -d 'n')
if [[ $counter -eq 35 ]]; then
printf '%dn' "${#currentString}"
break
fi
done
```

Make sure to use `printf` instead of `echo`, as it helps avoid issues with newlines that can mess up your count.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.