1

I am reading from csv file and echoing it line by line.

#!/bin/bash 
while IFS=";" read username first last password
do
echo "I got:$username $first $last $password"
if [ -z "$password" ]
then
    echo "null"
fi
done < users.csv

This is my csv file and for the null passwords null is not echoed.

lm;Lukáš;Masák;kjfask
spilk;Lukáš;Rasák;56456
kour;Lukáš;drtič;
hole;Lukáš;March;
lmmama;Lukáš;March;
ToklCz
  • 278
  • 3
  • 10
  • Please add a shebang and then paste your script at http://www.shellcheck.net/ and try to implement the recommendations made there. – Cyrus Apr 15 '21 at 17:52
  • The test comamnd should be `[ -z "$password" ]`... there is an empty espace before the closing bracket missing. – Alvaro Flaño Larrondo Apr 15 '21 at 17:54
  • shellcheck show everything alright after changing the if – ToklCz Apr 15 '21 at 17:59
  • There may be something invisible/nonprinting at the end of lines in your file. Is it in [DOS/Windows format](https://stackoverflow.com/questions/39527571/are-shell-scripts-sensitive-to-encoding-and-line-endings) (in which case unix tools will treat the lines as having nonprinting carriage returns at the end)? Are there spaces or tabs after the final ";" on those lines? Adding the command `set -x` at the beginning of the script will print a trace as it executes that might clarify what's going on. – Gordon Davisson Apr 15 '21 at 18:10
  • when using set -x, it shows that the variable is \r but if i compare it to it it still dont work – ToklCz Apr 15 '21 at 18:19
  • Well, `\r` obviously makes the `[ -z ... ]` test to fail. Obviously, your input file contains carriage return characters. I would convert it first using `dos2unix`. – user1934428 Apr 16 '21 at 06:34

1 Answers1

0

Comparison [ "$password" = $'\r'] worked. Thanks for that set -x.

suvayu
  • 4,271
  • 2
  • 29
  • 35
ToklCz
  • 278
  • 3
  • 10
  • I wouldn't recommend this solution. That test will fail if you get a file that isn't in DOS/Windows format, and with the current file the carriage return (the `\r`) will also be there on lines that *do* have passwords, and probably cause problems there. It's better to remove it than work around it. See the question I linked for possible solutions. You could also just use `while IFS=$';\r' read ...', and let the `read` command trim it for you. – Gordon Davisson Apr 15 '21 at 23:04