scripting

Björn Lindberg d95-bli at nada.kth.se
Tue Jul 13 11:40:01 PDT 2004


Bennett Todd <bet at rahul.net> writes:

> One basic issue to consider, is choice of tools.
> 
> If you care to, you can simplify scripts by using platform-specific
> aids like seq.
> 
> I, for one, tend to reach for perl when [relatively]
> platform-independent tools don't suit, as I and the folks I work
> with consistently provide that on all platforms we work on.
> 
> When the performance cost of doing so isn't too painful, I'll
> generally reach for expr(1), since it's always there. If I want a
> counted loop, and prefer to code it out rather than enumerating the
> results, I'll use
> 
> 	i=1
> 	while test $i -le 4;do
> 		echo file.$i
> 		i=`expr $i + 1`
> 	done
> 
> which brings up another choice-of-tools issue; some folk like to
> try, as a habit, to write scripts in the subset dialect that is
> pretty portable across platforms and across sh/bash/ksh/ash/....

Good point. When using shell, there are two reasonable portability
levels: plain Bourne shell or POSIX. Bourne shell is the lowest common
denominator, but I would guess that virtually every modern Unix
environment supplies at least one POSIX-compliant shell in addition to
the Bourne shell. It is, as you say, always a matter of needs, where
portability is only one of several factors. When I write scripts which
are intended to be portable, I limit myself to either plain Bourne or
to POSIX, but for local scripts intended for my own use only, I
generally use ksh93 or awk. Even with awk there is a choice of how
much portability you need. There is the original awk, or the "new
awk", called nawk on Solaris for instance, and finally GNU awk which
has a couple of extensions of its own. I imagine there are similar
problems with Perl too, since old installations may have older Perl
versions than currently is available?

> Another thing I find myself doing a lot is replacing shell loops
> with invocations of xargs, sometimes xargs -l. I also use perl a lot
> from the cmdline. So if I wanted to do
> 
> 	mv "file 1" file.1
> 	mv "file 2" file.2
> 		...
> 	mv "file 20" file.20
> 
> I'd probably go
> 
> 	perl -e 'rename "file $_","file.$_" for 1..20'
> 
> or perhaps
> 
> 	ls file*|perl -e 'rename $_,"file.$1" if / (\d+)$/'

I don't use Perl. I would instead use awk or shell or a combination
thereof. For the renaming above you could use the (not very portable)
rename utility. I would probably do

  for i in *; do mv "$i" ${i/ /.}; done


Björn



More information about the lfs-chat mailing list