Friday, September 2, 2022

[SOLVED] Retrieved character from string in bash script changes depending on the method

Issue

I'm learning shell scripting and found a very confusing situation:

  1. I retrieve all contents of the current directory using conteudo="$(ls)";
  2. Issuing echo $conteudo prints to the terminal "data emptydirectories.sh media obb", that's ok;
  3. 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;
  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.


Solution

The output "data emptydirectories.sh media obb" shown on the screen is not actually separated by space, those file names are separated by new line. If you do echo "$conteudo", you will see the true output. A simple way to convert those new lines to spaces is assigning it to another variable, aaa=$(echo $conteudo), then you will get your expected result.

$ conteudo="$(ls)"
$ echo $conteudo
access.log g_access_log.loh result.lst sublogs thislog.2020-02-25T10.28.01.956-f4b54c
$ echo "$conteudo"
access.log
g_access_log.loh
result.lst
sublogs
thislog.2020-02-25T10.28.01.956-f4b54c
$ conteudo=$(echo $conteudo)
$ echo "$conteudo"
access.log g_access_log.loh result.lst sublogs thislog.2020-02-25T10.28.01.956-f4b54c
$ echo `expr index "$conteudo" " "`
11
$ echo ${conteudo:0:1}
a


Answered By - WeDBA
Answer Checked By - Katrina (WPSolving Volunteer)