Home > OS >  bash setting variable getting error command not found
bash setting variable getting error command not found

Time:05-14

I'm writing one small bash script for my Project but i getting some errors

#!/bin/bash
count=$(cat Downloads/datei.csv | wc -l);
for((i=115;i<="122";i  )); do
line$i=$(sed -n $i"p" Downloads/datei.csv);
echo "line$i";
done

i trying to get every line from CSV in some variable

The erroŕ

count.sh: line 4: line115=: command not found

if [[ -z "line$i" ]];
then
      echo "$i is empty";
else
      echo "$i is NOT empty";
fi

the second code gives me the same error

CodePudding user response:

Suggest compose the code together, just update line$i to a temporary normal variable without other var like line_get.

One more thing, you need to update -z "line$i" to -z "$line_get". As in bash, you should use $ and the var name to get the value. Looks like:

#!/bin/bash
count=$(cat Downloads/datei.csv | wc -l)
for((i=115;i<=122;i  )); do
    line_get=$(sed -n $i"p" Downloads/datei.csv)
    if [[ -z "$line_get" ]];
    then
        echo "$i is empty"
    else
        echo "$i is NOT empty"
    fi
done

If you need to dynamic generate the variable name. Try this:

declare "line$i=$(sed -n $i"p" Downloads/datei.csv)" 
var="line$i"
echo "${!var}"

And echo "line$i"; just print the text like line115 but not the value of the variable line$1.

CodePudding user response:

How about using an array instead of variables with dynamic names? Also, calling sed inside the loop isn't very performant, you should extract the lines that you want in one fell swoop:

#!/bin/bash

lines=()
while IFS=',' read -r i line
do
    if [[ $line ]]
    then
        echo "$i is NOT empty"
    else
        echo "$i is empty"
    fi
    lines[i]=$line
done < <(
    awk -v OFS=',' -v from='115' -v to='122' '
        NR >= from && NR <= to {print NR, $0}
        END{ printf("%s",NR) }
    ' Downloads/datei.csv
)
count=$i

note: there's a little trick using the fact that read returns false for the last line when said line doesn't end with a newline character

  • Related