Hey everyone! I'm working on a Bash script that base64 encodes a string repeatedly, and I particularly need to check the length of the string at the 35th iteration of the loop. Here's the snippet I'm using:
```bash
#!/bin/bash
var="nef892na9s1p9asn2aJs71nIsm"
for counter in {1..40}
do
var=$(echo $var | base64)
# I want to check length when counter=35
done
```
What I want to achieve is to just print the length of `$var` when the loop hits iteration 35, without any extra text or newlines. I have tried using `${#var}`, but I'm not entirely sure where to place it. Also, `wc -c` counts extra unmatched bytes I don't need. Each time I try adding an if statement to check for the counter at 35, I keep getting unexpected results. Any suggestions for the cleanest way to get the exact character count at that moment?
5 Answers
To see if you’re doing this correctly, try running this command to check length:
```bash
var="nef892na9s1p9asn2aJs71nIsm"; for counter in {1..40}; do var=$(echo $var | base64); if [ $counter -eq 35 ]; then echo ${#var}; fi; done
```
This should give you the length at the specified counter.
Here’s a refined solution that should meet your needs:
```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
```
I recommend using `printf` instead of `echo` to avoid unintended newlines. This solution will give you exactly what you need—the length at iteration 35 without additional output options. Good luck!
You can definitely do it 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
```
Just remember to clear any potential newline characters during the base64 encoding with `tr -d 'n'`!
I think you might need to track the variable correctly:
```bash
for counter in {1..40}
do
v=$(echo $var | base64)
if [ $counter -eq 35 ]; then
echo ${#v}
fi
done
```
This way, you can see the length at iteration 35 without messing up the earlier values.
But if `var` keeps changing, how will you know the correct length for earlier iterations? That could lead to confusion.
You can also try this approach:
```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
```
This outputs a clean number without any newline issues. Don't forget the `--wrap=0` flag to prevent any wrapping that might mess with your output.
But why break the loop? You might want the results from the next iterations too.

Just to clarify, you need to avoid those newlines messing with your count!