0

I need to put the output of a certain command (three lines) in an array, here my script:

#!/bin/sh
while true ;
do
    res=($(top -n1 -p $(pidof "$1") | awk '{if (NR==1) print $3} {if (NR==8) print $9"\n"$10 }'));
    echo $res[0];
    echo $res[1];
    echo $res[2];
done;

I have checked this answer but when I run it with sh myScript.sh I get

myScript.sh: 6: myScript.sh: Syntax error: "(" unexpected (expecting "done")

Am I doing something wrong?

Community
  • 1
  • 1
onlycparra
  • 607
  • 4
  • 22
  • You aren't using bash as your shell. – Charles Duffy Jan 25 '16 at 23:12
  • `#!/bin/bash`, not `#!/bin/sh`, and `bash yourscript`, not `sh yourscript`. – Charles Duffy Jan 25 '16 at 23:13
  • (commented before than your second comment) Excuse me, I am actually just learning about bash, scripts and those magic tools like awk... Can you please explain me what do you mean? Why do you say I'm not using it? – onlycparra Jan 25 '16 at 23:16
  • See http://mywiki.wooledge.org/BashGuide/Practices#Choose_Your_Shell – Charles Duffy Jan 25 '16 at 23:17
  • Thanks for the wiki, it is very explicit "The first thing you should do before starting a shell script..." – onlycparra Jan 25 '16 at 23:18
  • I'm not clear as to whether that's sarcasm, but... "Always use the correct shebang. If you're writing a Bash script, you need to put `#!/usr/bin/env bash` at the top of your script. Omitting this header or using the `#!/bin/sh` header is wrong. In the latter case you will no longer be able to use any Bash features. You will be limited to the POSIX shell scripting standard (even if your `/bin/sh` links to Bash)." – Charles Duffy Jan 25 '16 at 23:39
  • Arrays are not part of the POSIX sh standard. Hence, if you need them to be available, you need to use a bash shebang, and (if invoking your script with an explicit interpreter) always use `bash` rather than `sh`. – Charles Duffy Jan 25 '16 at 23:40
  • Charles, it is not sarcasm, it was fun because I'm just learning, so to see "the first thing you should know" is fun for me. I have solved the problem, it was exactly what you pointed out. I ran `sh myScript.sh` and it had the header `#!/bin/sh`. Changed and it works smooth. Thanks again. – onlycparra Jan 26 '16 at 00:33
  • I will put the wrong header and the execution line to emphasize the mistake – onlycparra Jan 26 '16 at 00:35
  • Excellent, glad I was able to help! BTW, I might write `while true; do`, rather than `while [ true ]; do` -- the latter is simply testing whether `true` is an empty string or not; it would behave exactly the same way if you wrote `while [ false ]; do`, making it a bit misleading -- while `while true` is running the builtin command `true`, which is always unconditionally true. (The syntax for `while` takes a list of commands; `[` is a built-in command which behaves the same as `/usr/bin/[`, which behaves the same as `test` -- but any other command would work as well). – Charles Duffy Jan 26 '16 at 00:42

0 Answers0