script issue to fetch linux memory detail

  Kiến thức lập trình

Below script is not working on linux platform and it is giving an error as per below. Kindly check and help to fix the same.

Error-

sh LatestMem.sh (standard in) 1: illegal character: ^M (standard in) 1: illegal character: ^M

LatestMem.sh: line 5: $’r’: command not found.

LatestMem.sh: line 9: $’r’: command not found.

LatestMem.sh: line 18: syntax error: unexpected end of file –

Script-

#! /bin/bash

mem_tot=$(free -m|grep Mem|awk ‘{print $2}’)

mem_avlbl=$(free -m|grep Mem|awk ‘{print $7}’)

avlbl_per=$(echo “(“”$mem_avlbl”” / “”$mem_tot””)*100″ | bc -l | awk ‘{printf(“%.0fn”,$1)}’)

#echo $mem_tot

#echo $mem_avlbl

#echo $avlbl_per

if [ “$avlbl_per” -lt “10” ]

then

echo “Memory High Usage, Memory_Tot=$mem_tot, Memory_Avlbl=$mem_avlbl, Mem_Avlbl_Per=$avlbl_per”

else

echo “Memory Usage Below Threshold, Memory_Tot=$mem_tot, Memory_Avlbl=$mem_avlbl, Mem_Avlbl_Per=$avlbl_per”

fi

Tried to execute the below script on linux platform but getting error.

Script-

#! /bin/bash

mem_tot=$(free -m|grep Mem|awk ‘{print $2}’)

mem_avlbl=$(free -m|grep Mem|awk ‘{print $7}’)

avlbl_per=$(echo “(“”$mem_avlbl”” / “”$mem_tot””)*100″ | bc -l | awk ‘{printf(“%.0fn”,$1)}’)

#echo $mem_tot

#echo $mem_avlbl

#echo $avlbl_per

if [ “$avlbl_per” -lt “10” ]

then

echo “Memory High Usage, Memory_Tot=$mem_tot, Memory_Avlbl=$mem_avlbl, Mem_Avlbl_Per=$avlbl_per”

else

echo “Memory Usage Below Threshold, Memory_Tot=$mem_tot, Memory_Avlbl=$mem_avlbl, Mem_Avlbl_Per=$avlbl_per”

fi

The error you’re encountering, specifically the illegal character: ^M and unexpected end of file messages, indicates that your script has Windows-style line endings (rn) instead of Unix-style line endings (n). This often happens when scripts are written on a Windows system and then transferred to a Unix/Linux system without converting the line endings.

To fix this issue, you can convert the line endings to Unix format. One way to do this is by using the dos2unix command, which is a utility specifically designed for this purpose. If you don’t have dos2unix installed, you can typically install it using your package manager. For example, on Debian-based systems, you can use:

sudo apt-get install dos2unix

Once dos2unix is installed, you can use it to convert your script:

dos2unix LatestMem.sh

After converting the line endings, try running your script again:

sh LatestMem.sh

This should resolve the issues related to the illegal characters and unexpected end of file errors.

LEAVE A COMMENT