How to Make my R script executable?
Solution 1
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
Solution 2
If you want to point directly to the executable, then you need the full path after the shebang (no space):
#!/usr/bin/Rscript
As Ravi pointed out, if this fix doesn't work then the solution may just involve deleting the line break and putting it in again.
I'm not a fan of the env
workaround to make things more portable, because it makes the line more confusing and most people don't realise that it's actually calling another program (i.e. env
) to run the code in a modified shell. More information on that here.
k88074
Updated on June 06, 2022Comments
-
k88074 almost 2 years
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?