用bash修改工作目录



我使用knitr为一些bash命令制作降价报告。但是,我的操作包括更改一个目录并在那里创建一个文件,因此如果我可以在我的.Rmd文件中使用cd将是理想的:

make a directory
```{r mkdir, engine='bash'}
mkdir mytest
```
cd into directory
```{r cd, engine='bash'}
cd mytest
```
create file
```{r create, engine='bash'}
touch myfile
```
check contents
```{r ls, engine='bash'}
ls
```

但是,文件myfile是在我用knit编译文档的目录中创建的,而不是在mytest中。我猜每个代码块都会启动一个新的bash shell。

我看过关于在R (https://github.com/yihui/knitr/issues/277)中设置cwd的讨论,但没有在bash中设置。

是否有一种方法可以为代码块设置工作目录?

您可以使用Rscript来运行.Rmd文件,并在命令行中包含任何"R代码",以保持您的代码块完整。

Rscript -e "library(knitr); opts_knit$set(root.dir='~'); knit('test.Rmd')"是下面运行test.Rmd文件的bash命令示例。您可以更改root.dir以适应您的需要。

make directories
```{r mkdir, engine='bash'}
mkdir mytest
mkdir mytest2
```
create one file in the 1st dir
```{r create, engine='bash'}
cd mytest
touch myfile
```
create another file in the 2nd dir
```{r create2, engine='bash'}
cd mytest2
touch myfile2
```
check contents
```{r ls, engine='bash'}
ls mytest*
```
输出:

```
## mytest:
## myfile
##
## mytest2:
## myfile2
```

另一种方法是在你所在的位置创建每个文件夹和文件,而不是到处移动cd。

创建目录树

mkdir接受多个参数

mkdir -p 'plots/scatter' 'plots/box'
# creates plots folder in the working directory,
# and then creates scatter and box folders in it.

创建文件

touch 'plots/scatter/firstfile.txt' 'plots/scatter/secondfile.txt'
# single quotes mean literals

将关键部分保留为变量

从一个中心变量轻松更改文件夹结构:

scatter_folder=plots/scatter
touch "$scatter_folder/third_file.txt" "$scatter_folder/fourth_file.txt"
# double quotes allow for variable substitution.

最新更新