2

@terdon in this post answered the related question of mine, but I missed one more question in that post.

Plz refer to the following commands:

calc(){ awk "BEGIN{ print $* }" ;}; calc "((3+(2^3)) * 34^2 / 9)-75.89"

The above commands work fine with calculated result '1337'.

echo '((3+(2^3)) * 34^2 / 9)-75.89' | awk "BEGIN{ print $* }"

But the above commands don't give any result while @terdon explained well about why.

Could you advise what made the first example work with $*?

user58029
  • 141

1 Answers1

3

$* refers to positional parameters - those variables which are referenced by $1 and $2 and so on, and are provided as arguments to scripts and functions. That's the key to your question.

When you have interactive shell , there's no positional parameters set by default, so $* is empty. You can make it work if you set those via set "((3+(2^3)) * 34^2 / 9)-75.89" command, which will make $1 equal to that string.

The difference with calc(){ awk "BEGIN{ print $* }" ;}; is that it's a function and functions can process positional parameters (theirs, not the shell's). When you call calc "((3+(2^3)) * 34^2 / 9)-75.89" you're calling a function with positional parameter "((3+(2^3)) * 34^2 / 9)-75.89". There $* won't be empty:

$ calc(){ echo "Params: '$*'"; awk "BEGIN{ print $* }" ;}; calc "((3+(2^3)) * 34^2 / 9)-75.89"
Params: '((3+(2^3)) * 34^2 / 9)-75.89'
1337
terdon
  • 100,812
Sergiy Kolodyazhnyy
  • 105,154
  • 20
  • 279
  • 497