2

This is my script.

#!/bin/bash
MONITOR=$(free -m| grep Mem)
MEM_TOTAL=$(echo $MONITOR | awk '{ print $2 }')
MEM_USED=$(echo $MONITOR | awk '{ print $3 }')
MEM_FREE=$(echo $MONITOR | awk '{ print $4 }')
MEM_CACHE=$(echo $MONITOR | awk '{ print $5 }')
MEM_BUFFER=$(echo $MONITOR | awk '{ print $6 }')
declare -i MEM_UTIL=($MEM_TOTAL-($MEM_FREE+$MEM_BUFFER+$MEM_CACHE))
echo "$MEM_UTIL"

I got syntax errors such as

./memory_shell.sh: line 15: syntax error near unexpected token `('
./memory_shell.sh: line 15: `declare -i MEM_UTIL=($MEM_TOTAL-($MEM_FREE+$MEM_BUFFER+$MEM_CACHE))'

How can I fix it. I have 0 knowledge in shell scripting

1
  • 3
    shellcheck.net is your friend Commented Mar 29, 2016 at 8:53

2 Answers 2

3

Just to record my issue with exactly this error message. Turns out my scripts were DOS text files not Unix text files (as a result of a restore). DOS2Unix fix scripts and they ran fine with out this error. Your mileage may vary ....

Sign up to request clarification or add additional context in comments.

Comments

1

You just need to put quotes around the argument to declare -i as it takes one argument.

declare -i MEM_UTIL="($MEM_TOTAL-($MEM_FREE+$MEM_BUFFER+$MEM_CACHE))"

As you're using awk anyway, you may as well use it fully. The following does the same operation in awk:

#!/bin/sh
free -m | awk '/Mem/ {print($2 - ($4 + $5 + $6));}'

Awk can match the line for you as you are doing with grep and perform operations on the fields in the matched record. So rather than forking a number of subprocesses, you can fork one to process the output of the free command.

2 Comments

How can I get buffer and cache? MEM_BUFFER=$(echo $MONITOR | awk '{ print $6 }') is getting as buffer/cache. I have no idea to get separately. Actually this script getting MEM_CACHE=$(echo $MONITOR | awk '{ print $5 }') shared memory
If you need more parts parsed you will need to either return multiple values from the awk script and use the shell read function or continue with the exisiting script but use quotes to group the expression into a single argument. You've evidently only posted a fraction of the script so only you know which parts you will require.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.