Exhausted
Exhausted

Reputation: 1885

ksh while loop is behaving weird

I have the while loop in ksh which reads the file and loop through each line. Here is the same file contents (TestCases.txt)

TEST_PROC_1(1)/TEST_1,TEST_2,TEST_3/N/P
TEST_PROC_1(1)/TEST_1,TEST_2,TEST_3/N/N
TEST_PROC_2('CICD_DEMO.txt')/TEST_1,TEST_2,TEST_3/N/N
TEST_FUNC_1(100)/TEST_1,TEST_2,TEST_3/N/P
TEST_FUNC_2/TEST_1,TEST_2,TEST_3/N/N
TEST_PROC_4/TEST_1,TEST_2/N/N
TEST_FUNC_3(3)//N/P

The scripts which reads the document

swd=$(pwd)
export swd

file=${swd}/TestCases.txt

export testCaseIndex=1
export validateTblIndex=1

cat ${file} | while IFS=\/ read procname tablelist hold_data testcase_type
do
    echo "$procname $tablelist $hold_data $testcase_type"

    ksh ${swd}/assets/sh/main.sh "${procname}" "${tablelist}" "${hold_data}" "${testcase_type}" "${testCaseIndex}" "${validateTblIndex}"
    ret=$?
    echo $ret
    (( testCaseIndex+=1 ))
    (( validateTblIndex+=1 ))
done 

Here is the problem

If I comment the ksh call it iterates till last line.

TEST_PROC_1(1) TEST_1,TEST_2,TEST_3 N P
0
TEST_PROC_1(1) TEST_1,TEST_2,TEST_3 N N
0
TEST_PROC_2('CICD_DEMO.txt') TEST_1,TEST_2,TEST_3 N N
0
TEST_FUNC_1(100) TEST_1,TEST_2,TEST_3 N P
0
TEST_FUNC_2 TEST_1,TEST_2,TEST_3 N N
0
TEST_PROC_4 TEST_1,TEST_2 N N
0
TEST_FUNC_3(3)  N P
0

If I uncomment it stops with first line of the file.

TEST_PROC_1(1) TEST_1,TEST_2,TEST_3 N P
0

Kindly help out what could be possible issues. ksh call works fine even I run separately. I have ksh93 version.

Upvotes: 1

Views: 66

Answers (1)

chepner
chepner

Reputation: 532043

main.sh is also reading from standard input, which it inherits from the loop, so it is consuming data meant for the read command. Given that this surprises you, you may simply be able to redirect the script's standard input from /dev/null.

(Also, unless cat ${file} is just filling in for some other process that produces the data, use input redirection instead of a pipe.)

while IFS=/ read procname tablelist hold_data testcase_type
do
    echo "$procname $tablelist $hold_data $testcase_type"

    ksh ${swd}/assets/sh/main.sh "${procname}" \
       "${tablelist}" "${hold_data}" "${testcase_type}" \
       "${testCaseIndex}" "${validateTblIndex}" < /dev/null
    ret=$?
    echo $ret
    (( testCaseIndex+=1 ))
    (( validateTblIndex+=1 ))
done < $file

If main.sh does need to read from standard input, use a different file descriptor for read command.

while IFS=/ read procname tablelist hold_data testcase_type <&3
do
    echo "$procname $tablelist $hold_data $testcase_type"

    ksh ${swd}/assets/sh/main.sh "${procname}" \
       "${tablelist}" "${hold_data}" "${testcase_type}" \
       "${testCaseIndex}" "${validateTblIndex}" < /dev/null
    ret=$?
    echo $ret
    (( testCaseIndex+=1 ))
    (( validateTblIndex+=1 ))
done 3< $file

Upvotes: 2

Related Questions