1

Ohai, got another Bash problem.

for i in ${#input}; do echo ${input:$i:1}; done

works in the interactive bash, but not in a shell script. Input is a variable, based on an argument. It's set properly. Any ideas?

3

2 Answers 2

3

Not sure how it is working in interactive shell for you, this expression:

${#input}
  • will return number of characters in the first element if input is array variable
    otherwise
  • will return number of characters in the input variable

EDIT: based on your comments

I think you are trying to do this code:

for ((i=0; i<${#input}; i++))
do
   echo ${input:$i:1}
done

This code will iterate for each character in input string and then echo each character.

Sign up to request clarification or add additional context in comments.

3 Comments

But what is $i in this case? As per your code for loop will execute only once.
@thkala: lol :) I wish I had such power. But for i in ${#input}; made no sense and as per his code it just appeared to me perhaps he/she's trying to print input string character by character (of course I may be completely wrong).
Yep, that's what I try to do. $i is the counter of a for loop.
2

I cannot see the purpose of this piece of code - it's equivalent to a single echo.

Explanation:

${#input} is the length of the contents of the input variable. It is always a single number, hence the loop will always be executed once. $i is then modified to contain that variable length.

Then ${input:$i:1} means "1 character from the input variable, starting at offset $i, which is equal to the length of the variable, and, therefore, past its end. I.e. ${input:$i:1} is always an empty string. So your code can be simplified to:

echo

As an example, if $input is foobar, then ${#input} is 6, and your loop executes once this command: echo ${input:6:1}. Offsets here are zero-based, therefore 6 is just past the last character of $input. If you are trying to get the last character of a variable, try this:

$ input=foobar; echo ${input:${#input}-1:1}
r

What exactly are you trying to do?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.