9

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.

3
  • Are you actually looking for $@ (array of positional args) in bash? Commented Apr 3, 2020 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. Commented Apr 3, 2020 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 Commented Apr 13, 2022 at 15:39

1 Answer 1

7

Try

!cp $foo $bar

Without the braces.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.