Need help for shell script

Hi Guys,

I am new to shell scripting and trying out a simple shell script.

  1. Grep "MemTotal" from /proc/meminfo store it in "mem" variable.
  2. Extract digits in the same order from "mem" variable, store in to "mem_digit".
  3. Divide the captured value from 1024 to get in MB, store in "mem_mb".
  4. Display value from "mem_mb".
#!/bin/bash

mem=`(cat /proc/meminfo | grep MemTotal)`
mem_digit=`(echo "$var" | /usr/bin/tr -cd [:digit:])`
mem_mb=$(($mem_digit/1024))
echo "System RAM : $mem_mb MB"

While running this shell script i am getting below error:

[root@localhost bash]# ./demo.sh
./demo.sh: line 5: /1024: syntax error: operand expected (error token is "/1024")
System RAM :  MB

But when i am trying same lines of code 1 by 1 on the direct console i am able to get the correct output.

[root@localhost bash]# mem=`(cat /proc/meminfo | grep MemTotal)`
[root@localhost bash]# mem_digit=`(echo "$var" | /usr/bin/tr -cd [:digit:])`
[root@localhost bash]# mem_mb=$(($mem_digit/1024))
[root@localhost bash]# echo " System RAM : $mem_mb MB"
 System RAM : 1869 MB

Could you guys please point out if i have missed something in the script ?

-Ashish:confused:

In the script the var variable does not get set. When you try the lines one by one it probably does have a value. Try:

echo "$var"

Probably you meant to use the mem variable.

mem_digit=`(echo "$mem" | /usr/bin/tr -cd [:digit:])`
1 Like

Working. thanks for figuring out typo :slight_smile:

-Ashish

Got an error in above code .There is no variable named var defined in your code.Re-check that.Below works as expected

#!/bin/bash
#var=1024
mem=`(cat /proc/meminfo | grep MemTotal)`
mem_digit=`(echo "$mem" | /usr/bin/tr -cd [:digit:])`
echo $mem_digit
mem_mb=$(($mem_digit/1024))
echo "System RAM: $mem_mb MB"
1 Like

Here is just 1 long line

sysmem=$(($(cat /proc/meminfo | grep 'MemTotal' | tr -s ' ' | cut -d' ' -f2) / 1024))