RE: [PATCH 3/3] kbuild: rewrite ld-version.sh in shell script

From: David Laight
Date: Mon Dec 21 2020 - 09:53:29 EST


From: Masahiro Yamada
> Sent: 21 December 2020 14:29
>
> On Sun, Dec 13, 2020 at 6:47 AM David Laight <David.Laight@xxxxxxxxxx> wrote:
> >
> > From: Masahiro Yamada
> > > Sent: 12 December 2020 16:55
> > >
> > > This script was written in awk in spite of the file extension '.sh'.
> > > Rewrite it as a shell script.
> > ...
> > > +#
> > > +# Usage: $ ./scripts/ld-version.sh ld
> > > +#
> > > +# Print the linker version of `ld' in a 5 or 6-digit form
> > > +# such as `23501' for GNU ld 2.35.1 etc.
> > > +
> > > +first_line="$($* --version | head -n 1)"
> > > +
> > > +if ! ( echo $first_line | grep -q "GNU ld"); then
> > > + echo 0
> > > + exit 1
> > > +fi
> > > +
> > > +# Distributions may append an extra string like 2.35-15.fc33
> > > +# Take the part that consists of numbers and dots.
> > > +VERSION=$(echo $first_line | sed 's/.* \([^ ]*\)$/\1/' | sed 's/^\(^[0-9.]*\).*/\1/')
> > > +MAJOR=$(echo $VERSION | cut -d . -f 1)
> > > +MINOR=$(echo $VERSION | cut -d . -f 2)
> > > +PATCHLEVEL=$(echo $VERSION | cut -d . -f 3)
> > > +printf "%d%02d%02d\\n" $MAJOR $MINOR $PATCHLEVEL
> >
> >
> > Hmmmm.....
> > You've managed to convert an awk script into something that requires
> > sh, head, grep, sed (twice), and cut (thrice).
> > Plus (probably) a few sub-shells.
> >
> > It is quite ease to do it all in all in the shell.
> >
> > David
> >
>
> OK, please rewrite the code.

I've posted a couple of versions before, how about this one.
I've added a few comments - which don't need to be in the final version.

# Get the first line of the 'ld --version' output
if input_from_from_stdin; then
read line
else
IFS='
'
set -- $("$@")
line="$1"
fi

# Split the line on 'space' and get the last word
IFS=' '
set -- $line
shift $(($# - 1))
version="$1"

# Split on '.' and '-'
IFS='.-'
set -- $version

# The three version components are now $1 $2 and $3
# so you can do either
printf "%d%02d%02d\\n" $1 $2 $3
# or
echo $(($1 * 10000 + $2 * 100 + $3))
# both are builtins on recent shells (printf is most likely not to be).

So this should be the same as the script above:

#! /bin/sh
IFS='
'
set -- $("$@")
# The last word contains the version
IFS=' '
set -- $1
shift $(($# - 1))
# Get the first 3 parts of the version
IFS='.-'
set -- $1
printf "%d%02d%02d\\n" $1 $2 $3

Seems to work for me.

David

-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK
Registration No: 1397386 (Wales)