I'm learning to script in bash, trying to solve a little exercise. The exercise is this:
If the variable named "basenew" contains the contents of the variable named "valuebase". "basenew" must contain more than 113,469 characters. If both conditions are met, the script must then print the last 20 characters of the variable "basenew".
My code is
#!/bin/bash
basenew="8dm7KsjU28B7v621Jls"
valuebase="ERmFRMVZ0U2paTlJYTkxDZz09Cg"
for i in {1..40}
do
basenew=$(echo $basenew | base64)
if [[ $basenew =~ $valuebase && ${#basenew} -ge 113469 ]] ; then
echo $i
echo $basenew | wc -c
StrLen=`echo ${basenew} | wc -c`
From=`expr $StrLen - 20`
echo $basenew | cut -c ${From}-${StrLen}
else
echo "error"
fi
done
But I'm stuck, because it prints in the 28th iteration, and it is the 20 last, but it isn't the correct answer.
Any advice to print the last 20 characters using tail -c 20?
Thanks
${#basenew}
, so whyecho $basenew | wc -c
too? 3) look into the substring expansion${var:pos:count}
, so you don't need thecut
. Also arithmetic expansion$(( ... ))
, no need forexpr
. 4) quote the variable expansions, see When is double-quoting necessary? and http://mywiki.wooledge.org/WordSplittingerror
since you are just repeating the exact same comparison 48 times:if [[ $basenew =~ $valuebase && ${#basenew} -ge 113469 ]]
. Your variables$basenew
and$valuebase
never change value, so this is probably not the actual script you are asking about. Please [edit] your question and show us the actual script you are using that "prints in the loop 28". – terdon Aug 17 '21 at 12:22U2paTlJYTkxDZz09Cg==
the wrong output? – terdon Aug 17 '21 at 14:34For the use of "tail -c 20" i need to save the output inside a .txt?
– joop Aug 17 '21 at 14:40b64=$(printf %s "$var" | base64 -w0)
.echo
adds a newline character, mangles backslashes and/or some values starting with-
(though the last two won't occur here). – Stéphane Chazelas Aug 17 '21 at 14:46basenew
on each iteration, but we don't see the description of how that should be done and can't check if the script is doing it correctly. Remember: it's your exercise, pretty much no-one else can know what exactly should be done, so you might want to take care to tell the details correctly and in full. – ilkkachu Aug 17 '21 at 15:21