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
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.
**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!
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.
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
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically
[Centos] Delete All Files And Folders That Contain a String