Introduction to Bash

Hello all,
I currently having issues with the first task of Introduction to Bash Scripting on the HTB Academy platform.
Here is the code in question:

#!/bin/bash
# Count number of characters in a variable:
#     echo $variable | wc -c

# Variable to encode
var="nef892na9s1p9asn2aJs71nIsm"

for counter in {1..40}
do
        var=$(echo $var | base64)
done

The question is " Create an “If-Else” condition in the “For”-Loop of the “Exercise Script” that prints you the number of characters of the 35th generated value of the variable “var”. Submit the number as the answer."

I tried many different approaches but keep getting the wrong answers. Can someone nudge me on the right direction?
Here is my code:

 #!/bin/bash

# Variable to encode
var="nef892na9s1p9asn2aJs71nIsm"

for counter in {1..40}
do
    var=$(echo -n $var | base64 -w 0)

    if [ $counter -eq 35 ]; then
        num_chars=${#var}
        echo "Number of characters in the 35th encoded value: $num_chars"
    fi

done

Thanks in Advance.

1 Like

Thank you for your reply.
That code did not work right away(Illegal number: {1…40}) but I found a workaround.

var="nef892na9s1p9asn2aJs71nIsm"

for ((counter=1; counter<=40; counter++))
do
  var=$(echo $var | base64)
  if [ $counter -eq 35 ]
  then
    echo "The number of characters of the 35th generated value of the variable var is: $(echo $var | wc -c)"
  fi
done

I sincerely appreciate the help @marek33366
Cheers

1 Like

no problem good job for your debug

1 Like

I thought I would add a bit more context to this for any future readers, as I was a bit confused about how this worked, to begin with.

Here is a solution with some explanatory comments.

#!/bin/bash
# Count number of characters in a variable:
#     echo $variable | wc -c

# Variable to encode
var="nef892na9s1p9asn2aJs71nIsm"

for counter in {1..40}  # The `for` loop iterates 40 times.
do
	var=$(echo $var | base64)  # `var` piped into the `base64` command & the output reassigned to `var`.
    	if [[ $counter -eq 35 ]] # Conditional if statement checks if the iteration number (counter) is 35.
    	then
    		echo $(echo $var | wc -c)
# This part sends the content of var to wc -c, which counts the number of characters.
#  $(...) is a command substitution. The shell first executes the command inside the parentheses and then replaces $(...) with the output of that command.
# echo $(...) then outputs the result of the command substitution.
    	fi
done
1 Like