Search code examples
rshebangrscript

How to Make my R script executable?


I am aware this is at high risk of being a duplicate, but in none of the other questions here I have found an answer to my problem. Below is a summary of what I have already tried.

I have an R script file file.r:

#!/usr/bin/env Rscript 
print("Hello World!")

which is executable (chmod +x file.r), and which used to run nicely (last time I used it was about a month ago) by issuing:

$ ./file.r

However, today:

$ ./file.r
/usr/bin/env: 'Rscript\r': No such file or directory

In fact:

$ which Rscript
/usr/bin/Rscript 

Thus I changed shebang to: #!/usr/bin Rscript, but:

$ ./file.r
/usr/bin: bad interpreter: Permission denied

Then I thought I would run it as super user, but:

$ sudo ./file.r
sudo: unable to execute ./file.r: Permission denied

Reading around I found that a fresh installation of R would solve my problem, so I un-installed and installed R. Unfortunately what I have written before still applies. Notice however that the following works with both shebang versions:

$ Rscript file.r
[1] "Hello World!"

What am I doing wrong?


Solution

  • Ah, Its carriage return (\r) issue, It's added to the first line, if you are using vi editor, :set list will show it. line endings will be shown as $ and carriage return chars as ^M.

    #!/usr/bin/env Rscript  Makes your script portable than #!/usr/bin/Rscript
    

    Btw, you can insert \r in vi by going into insert(i)/Append(a) mode and type ctrl+v and then ctrl+m