1825639 Members
3649 Online
109683 Solutions
New Discussion

Script Explaination

 
SOLVED
Go to solution
Allanm
Super Advisor

Script Explaination

I am looking at an old script which has the following text which I dont understand...

set -- `< /tmp/c.1`
q=$*
printf "%s\n" $(( ${q// / + } )) > /tmp/c.2

Can someone please explain what this is doing?

Thanks,
Allan.
2 REPLIES 2
James R. Ferguson
Acclaimed Contributor
Solution

Re: Script Explaination

Hi Allan:

# set -- `< /tmp/c.1`

...sets the shell's positional parameters $1, etc. to the contents of the file '/tmp/c.1'. If that contained a line with the string "a b c d e f", then $1 would be "a"; $2 would be "b", etc.

A better form is:

# set -- $(
...eliminating the archaic backtick syntax.

# q=$*

...simply creates a string called 'q' which contains all the positional paramters.

# printf "%s\n" $(( ${q// / + } )) > /tmp/c.2

...frankly, I don't quite know what this is attempting to do. Post the contents of your input file.

Regards!

...JRF...
James R. Ferguson
Acclaimed Contributor

Re: Script Explaination

Hi (again) Allanm:

OK, you're using a Bash shell, I believe. The third statement sums numbers. Blanks are converted to the operator needed to sume (the '+') and the whole expression is evaluated. One could just as easily do subtraction or multiplication by changing the '=' to a '-' or '*' respectively.

For instance, given:

# set -- 1 2 3 4 5 6
# q=$*
# printf "%s\n" $(( ${q// / + } ))
21

Or, with a bit of Perl:

# echo ${q}|perl -nle '@a=split;print eval join "+",@a'
21

As with the pure shell, one could do subtraction or multiplication by changing the '=' to a '-' or '*' respectively.

Regards!

...JRF...