0

I have a bash code which assigns all files into a variable, splits the string by a space and loops over them like this:

$ ls
README  db_password.example  db_username.example
files_str=$(ls)
files=(${files_str// /})

for file in "${files[@]}"; do 
  if [ "$file" != "README" ]; then 
    echo "$file is not README";
  fi; 
done;

output:

enter image description here

I think now that it is something with data types. I thought bash only has strings? I guess I was mislead, maybe by similar sources like this: https://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-5.html#:~:text=There%20are%20no%20data%20types,its%20reference%20will%20create%20it.

But when I do

file=README
if [ "$file" != "README" ]; then 
  echo "$file is not README";   
fi;`

I get no output which is correct. So how do I make it work with ls?

3
  • 2
    You probably have an alias for "ls" to add the color, which is produced with additional control chars, which of course mess up the string compare. Try /bin/ls or ls --color=none
    – ubfan1
    Jun 17, 2022 at 21:44
  • 1
    Always paste your script into https://shellcheck.net, a syntax checker, or install shellcheck locally. Make using shellcheck part of your development process.
    – waltinator
    Jun 17, 2022 at 23:32
  • @ubfan1 you are absolutely right. I have an alias "ls --color" and your suggestion worked, thank you. This is why string didnt compare I guess because color are the character like \e[m etc.. I didn't realise that! Jun 18, 2022 at 9:00

1 Answer 1

2

You probably have an alias for "ls" to add the color, which is produced with additional control chars, which of course mess up the string compare. Try /bin/ls or ls --color=none instead of just ls.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .