I have the following code
#!/bin/bash
declare -i max
exec < lista.csv
read header
max=0
while IFS=, && read -r id _ _ _ _ _
do
if [ "$id" -gt "$max" ]
then
max=$id
fi
done
((id=max 1))
read -p "Nume: " nume
echo "Prenume: "
read prenume
echo "Grupa: "
read grupa
echo "Seria: "
The problem is when I run it the it doesn't let me input a value, and in the CSV file there is something like this:
44,,,,,
CodePudding user response:
The exec
command redirects standard input for the remainder of the script, so all the read
commands end up reading from your file handle, which is quickly starting to return empty lines when all the data in the file is consumed.
You also want to avoid resetting IFS for the remainder of your script; IFS="," read
temporarily overrides its value just for the duration of the read
command. (Thanks Fravadona for mentioning this in a comment.)
Apparently you are looking for something like
#!/bin/bash
declare -i max
exec 3< lista.csv
read -u 3 header
max=0
while IFS=, read -u 3 -r id _ # no need to put many _ if you don't use them; the last one will simply contain the remaining fields
do
if [ "$id" -gt "$max" ]
then
max=$id
fi
done
((id=max 1))
read -p "Nume: " nume
echo "Prenume: "
read prenume
echo "Grupa: "
read grupa
echo "Seria: "
... though a much better solution is probably
#!/bin/bash
declare -i id
id=$(awk -F, 'NF==1 { next } NF==2 || max>$1 { max=$1 } END { print max 1 }' lista.csv
read -p "Nume: " -r nume
read -p "Prenume: " -r prenume
read -p "Grupa: " -r grupa
echo "Seria: "
If you are trying to reimplement the adduser
command, maybe see if it's already implemented (Debian and Arch both have a command with this name, though their heritages are different IIFC) and/or if you can get it to print messages in your language by setting your locale
.