6

I would like to run bash commands in jupyter notebook using the %%bash magic command and pass python variables. As described in this post I can do this as follows:

%%bash -s {foo} {bar}
cp $1 $2

This works just fine. However, when I have a bunch of these variables and the bash commands are long, it becomes a bit unwieldy to use $1, $2, and so on for arguments. I know that one can use the curly braces notation for line magics as follows:

!cp {foo} {bar}

Is there a comparable way to use the curly brace notation with cell magic? Perhaps something along the lines of:

## in a python cell
foo = 'foo.txt'
bar = 'bar.txt'

## in another cell
%%bash <SOMETHING GOES HERE>
cp {foo} {bar}

UPDATE (04-14-2022): This can be done by defining a new magic as described here.

vkkodali
  • 630
  • 7
  • 18
  • Are you actually looking for `$@` (array of positional args) in bash? – jordanm Apr 03 '20 at 16:40
  • `$@` is going to return the entire list of arguments. But what I am interested in is to be able to refer to them using a name instead of numbers. I will edit the question to make it a little more clear. – vkkodali Apr 03 '20 at 18:21
  • Question answered by @krassowski in the post referred to by the question author (about a year after the question was asked here) TLDR: Basically, you can use Python string templates with braces if you are willing to define new cell magic – Kleber Noel Apr 13 '22 at 15:39

1 Answers1

6

Try

!cp $foo $bar

Without the braces.

Stephen Wood
  • 1,257
  • 1
  • 12
  • 13