How to show line number when executing csh script?

2019-08-02 06:03发布

问题:

I am using csh script and I want to see the line numbers when executing csh script in debug mode. I am doing like

csh -x script_name

What do I have to do apart from this to see line numbers in debug mode?

回答1:

There is no built-in feature to do this. The only method I can think of is (ab)using the postcmd special alias. This alias will be run after every command:

set _lineno = 0
alias postcmd '@ _lineno++ && echo -n $_lineno\ '

echo a
echo b
echo c && echo d

Outputs:

% csh test.csh
1 2 a
3 b
4 c
d

Unfortunately, this will clutter the -x output:

% csh -x test.csh
set _lineno = 0
alias postcmd @ _lineno++ && echo -n $_lineno\ 
@ _lineno++
echo -n 1 
1 @ _lineno++
echo -n 2 
2 echo a
a
@ _lineno++
echo -n 3 
3 echo b
b
@ _lineno++
echo -n 4 
4 echo c
c
echo d
d

Which we can sort of filter with grep:

% csh -x test.tcsh | & grep -Ev '^(@ _lineno|echo -n [[:digit:]]+)
set _lineno = 0
alias postcmd @ _lineno++ && echo -n $_lineno\ 
1 @ _lineno++
2 echo a
a
3 echo b
b
4 echo c
c
echo d
d

All of this is less than perfect, and may not even work very well with large scripts...

As you've asked a number of csh related questions for the last few days:

While tcsh can work fine as an interactive shell, tcsh or csh is generally not well suited for scripting tasks. There are many things missing, incomplete, or simply behave in a "strange" way. It's even more ugly than normal shell scripting with POSIX (and that's saying a lot).

Unless you have a good reason not to (such as maintaining existing scripts), you probably should give up on csh for now, and go with either a "real" programming language (Python, Ruby, Perl, whatever), or use /bin/sh, bash, or zsh.



标签: linux shell csh