I'm learning shell scripting and found a very confusing situation:
- I retrieve all contents of the current directory using
conteudo="$(ls)"; - Issuing
echo $conteudoprints to the terminal "data emptydirectories.sh media obb", that's ok; - Then the script must run
echo `expr index "$conteudo" " "`, which prints zero to the terminal, what got me already confused, 'cause I expected it to print 4; - The the last command is
echo ${conteudo:0:1}, which prints "d" in the terminal (clown face).
I want to understand why the character changes in the two situations. I first imagined that the quotation was interfering in the way the string is being processed, but haven't found anything about it, and changing the quotation use either makes no effect or returns errors.
ls?conteudodoesn't contain any spaces; it has newlines between filenames, butecho $conteudoshows spaces because the variable isn't double-quoted. See "I just assigned a variable, butecho $variableshows something else" and "When should I double-quote a parameter expansion?" (short answer: almost always). shellcheck.net is good at pointing out this and a number of other common mistakes.