-1

Trying to execute this shell script.

#!/bin/bash
# Proper header for a Bash script.

# Cleanup, version 2

# Run as root, of course.
# Insert code here to print error message and exit if not root.

LOG_DIR=/var/log
# Variables are better than hard-coded values.
cd $LOG_DIR

cat /dev/null > messages
cat /dev/null > wtmp


echo "Logs cleaned up."

exit #  The right and proper method of "exiting" from a script.
     #  A bare "exit" (no parameter) returns the exit status
     #+ of the preceding command.
~

But getting this message

[root@localhost ~]# ./clean.sh
-bash: ./clean.sh: /bin/bash^M: bad interpreter: No such file or directory

Any idea what's going on?

truthtriumphs
  • 59
  • 1
  • 10

2 Answers2

6

Your script has DOS line endings. Convert them to Linux line endings either in your editor or with tools like dos2unix, recode etc.

DOS/Windows usually ends lines with CR+LF, while Linux only uses LF. The shell doesn’t know what to make out of the additional CR character and displays it as ^M.

Sven
  • 98,649
  • 14
  • 180
  • 226
  • I used Notepad++ to copy and paste the code. Then I moved it to the Linux box – truthtriumphs Mar 03 '19 at 12:03
  • Thanks Sven. I made changes in Notepad++ , In the menu under 'Edit' there is an option 'EOL > Linux format' I enabled that. It's working now. It's saved as .bash though.. – truthtriumphs Mar 03 '19 at 12:23
2

you need to check file encoding, seems you have edited your bash script from windows, then move the file to Linux. to fix this issue you have three solution
1- use dos2unix to change file encoding
2- copy the content of the file and past it into new one
3- change file encoding using any script editor from Windows then move it again to Linux

Ahmad Abuhasna
  • 195
  • 1
  • 9
  • Thanks Ahmad. That's what I exactly did. I used Notepad++ and then moved the file. – truthtriumphs Mar 03 '19 at 12:03
  • @truthtriumphs notepad++ use by default Windows unicode which will not help you, you need to use more advanced editor such as 010 editor this will do the convation for you. – Ahmad Abuhasna Mar 03 '19 at 12:17
  • Thanks Ahmad. I made some changes. Notepad++ has the option to convert to EOL > Linux format. I made the changes and it worked. Thanks for your input. – truthtriumphs Mar 03 '19 at 12:20