stringbashfunctionshelleval

Reading a text file and using each line as an input for a function


I have a file in which there are more than thousand lines and in each line there is a string of 12 characters. I also have a script in which there is a function. I want the file to be read every time the function is executed and the first 8 characters of each line of this file will be received as input and the function will be executed for each line of the file. I'd checked similar topics but they didn't help me. I don't have the possibility to use Python, Jason and other languages ​​and libraries except shell script. The script I wrote is as follows, which seems to work correctly, but returns an error:

#!/bin/bash
input_file="input.txt"
while IFS= read -r line; do
# Extract the first 8 characters from the line
code="${line:0:8}"
# Dynamically build the command and execute it
eval "filterTxtforfunc(\$0,\"$code\")"
done < "$input_file"

An Err:

-bash: eval: line 12: syntax error near unexpected token `$0,"PRI3ZNPZ"'

-bash: eval: line 12: `filterTxtforfunc($0,""PRI3ZNPZ")'

The filterTxtforfunc($0,""PRI3ZNPZ") is exactly what I want to generate automatically and use automatically in my script.

input.txt is like this:

WRM3BHIZ0004
NRB1SAPB0122
LRT1SYGM0114
KRF1LAEI0451
JRU1TEEE0764
ZRQ1LQWS0666
PRH1DCHK0904
...

Solution

  • Bash is not python. In bash a function call is just a command. There is nothing dynamic about it.

    filterTxtforfunc() {
       echo does something
    }
    input_file="input.txt"
    while IFS= read -r line; do
       # Extract the first 8 characters from the line
       code="${line:0:8}"
       # Dynamically build the command and execute it
       filterTxtforfunc "$0" "$code"
    done < "$input_file"
    

    Consider researching an introduction to bash and bash functions. Remember to check your scripts with shellcheck.