Srinivas Nallapati
Srinivas Nallapati

Reputation: 155

how to detect line number of output of shell script

I am using below script ,

clear
tput cup 1
echo "1";
tput cup 2
echo "2";
tput cup 4
echo "3";

then Out put is coming like

1
2
3

If i use wrong script like ,

clear
tput cup 1
echo "1";
tput cup 2
echo ;"2";
tput cup 3
echo "3";

then out put is

1

3/var.sh: line 5: 2: command not found

This means in third line 3 printed and 2 line error also printed . So is there any way to detect error line number to print 3 after error?

EDIT:

when I use -x , output is

[root@srinivas Installation]# sh -x  var.sh 
+ clear







+ tput cup 1
+ echo 1
+ echo
+ echo 3up 2
3 2
[root@srinivas Installation]#  found
+ tput cup 3

Upvotes: 0

Views: 1165

Answers (3)

twalberg
twalberg

Reputation: 62369

That output looks like what should be expected. Here's the sequence:

tput cup 1
echo "1"

Move to line 1 and output a 1. This works properly.

tput cup 2
echo ;"2";

Move to line 2, then output a blank line (echo with no arguments) which moves to line 3. Then execute a program named 2, which the script can't find, resulting in the error message ./var.sh: line 5: 2: command not found printed on line 3.

tput cup 3
echo "3";

Move to line 3 and output a 3, which overwrites the . in the above error message. Resulting in the final apparent output that you note, even though it wasn't produced in a strictly left-to-right top-to-bottom order.

Upvotes: 1

l0b0
l0b0

Reputation: 58768

This is because standard output and standard error are printed in different ways - Standard output is synchronous, meaning the lines will be printed in sequence and as they arrive, while standard error is asynchronous, which means it's printed whenever the terminal can fit it in. One way to fix this is to chunk standard error together with standard output:

/var.sh 2>&1

More details in Greg's wiki.

PS: All the semicolons in the file are unnecessary - If your commands are separated by newlines, semicolons will never be necessary.

Upvotes: 0

Brian Agnew
Brian Agnew

Reputation: 272217

If you run your shell script with the -x option, it'll show you each line as it executes.

Upvotes: 2

Related Questions