A cosmetic improvement to the output of system
can be obtained by wrapping the call in cat
and specify '\n'
as the separator, which displays the output on separate lines instead of separated by whitespaces which is the default for character vectors. This is very useful for commands like tree
, since the format of the output makes little sense unless separated by newlines.
Compare the following for a sample directory named test
:
Bash
$ tree test
test
├── A1.tif
├── A2.tif
├── A3.tif
├── README
└── src
├── sample.R
└── sample2.R
1 directory, 6 files
R in Jupyter Notebook
system
only, difficult to comprehend output:
> system('tree test', intern=TRUE)
'test' '├── A1.tif' '├── A2.tif' '├── A3.tif' '├── README' '└── src' ' ├── sample.R' ' └── sample2.R' '' '1 directory, 6 files
cat
+ system
, output looks like in bash:
> cat(system('tree test', intern=TRUE), sep='\n')
test
├── A1.tif
├── A2.tif
├── A3.tif
├── README
└── src
├── sample.R
└── sample2.R
1 directory, 6 files
Note that for commands like ls
, the above would introduce a newline where outputs are normally separated by a space in bash.
You can create a function to save you some typing:
> # "jupyter shell" function
> js <- function(shell_command){
> cat(system(shell_command, intern=TRUE), sep='\n')
> }
>
> # brief syntax for shell commands
> js('tree test')