You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rscript命令中使用here文档?

问题现象

用here文档替代文本文件的方式在python中可以正常运行:

(base) balter@exahead1:~$ python <<EOF
print("hello")
EOF
hello

但该方式直接用于Rscript会触发帮助信息,无法正常执行:

(base) balter@exahead1:~$ Rscript <<EOF
print("hello")
EOF
Usage: Rscript [options] file [args]
   or: Rscript [options] -e expr [-e expr2 ...] [args]
A binary front-end to R, for use in scripting applications.

Options:
  --help              Print usage and exit
  --version           Print version and exit
  --verbose           Print information on progress
  --default-packages=LIST  Attach these packages on startup;
                        a comma-separated LIST of package names, or 'NULL'
and options to R (in addition to --no-echo --no-restore), for example:
  --save              Do save workspace at the end of the session
  --no-environ        Don't read the site and user environment files
  --no-site-file      Don't read the site-wide Rprofile
  --no-init-file      Don't read the user R profile
  --restore           Do restore previously saved objects at startup
  --vanilla           Combine --no-save, --no-restore, --no-site-file,
                        --no-init-file and --no-environ

Expressions (one or more '-e <expr>') may be used *instead* of 'file'.
Any additional 'args' can be accessed from R via 'commandArgs(TRUE)'.
See also  ?Rscript  from within R.

而通过文本文件的方式可以正常运行:

(base) balter@exahead1:~$ cat test.R
print("hello")
(base) balter@exahead1:~$ Rscript test.R
[1] "hello"

解决方法

要在Rscript中用here文档执行脚本,只需在命令中添加-(代表读取标准输入),明确告知Rscript从标准输入获取代码内容:

(base) balter@exahead1:~$ Rscript - <<EOF
print("hello")
EOF
[1] "hello"

原理是Rscript默认需要指定文件名作为参数,传入-后,它会将here文档的内容作为脚本执行,完美适配多行代码场景。

如果是单行代码,也可以用-e参数实现,但here文档更适合多行脚本的编写:

Rscript -e 'print("hello")'

内容的提问来源于stack exchange,提问作者abalter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 07:52:18