2

I wonder why it doesn't work. Please advise me.

1. working

$ nu=`awk '/^Mem/ {printf($2*0.7);}' <(free -m)`
$ echo $nu
1291.5

2. not working

$ cat test.sh
#!/bin/bash
nu=`awk '/^Mem/ {printf($2*0.7);}' <(free -m)`
echo $nu
$ sh test.sh  
test.sh: command substitution: line 2: syntax error near unexpected token `('
test.sh: command substitution: line 2: `awk '/^Mem/ {printf($2*0.7);}' <(free -m)'
Inian
  • 80,270
  • 14
  • 142
  • 161

3 Answers3

3

Could you please try following.

nu=$(free -m | awk '/^Mem/ {print $2*0.7}')
echo "$nu"

Things taken care are:

  • Use of backtick is depreciated so use $ to store variable's value.
  • Also first run free command pass its standard output as standard input to awk command by using |(which should be ideal way of sending output of a command to awk in this scenario specially) and save its output to a variable named nu.
  • Now finally print variable nu by echo.
  • Since <(...) process substitution is supported by bash not by sh so I am trying to give a solution where it could support without process substitution (which I mentioned a bit earlier too).
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
2

The <( ) construct ("process substitution") is not available in all shells, or even in bash when it's invoked with the name "sh". When you run the script with sh test.sh, that overrides the shebang (which specifies bash), so that feature is not available. You need to either run the script explicitly with bash, or (better) just run it as ./test.sh and let the shebang line do its job.

Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151
1

The reason to add a shebang in a script is to define an interpreter directive if the file has execution permission.

Then, you should invoke it by, for example

$ ./test.sh

once you have set the permission

$ chmod +x test.sh
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134