38

I have a cell with this content:

import os
os.mkdir('123')
name = '123'
!rm -r name

I want to pass the value of the variable name to the last line. How can I do this?

me2 beats
  • 774
  • 1
  • 8
  • 24

2 Answers2

67

Try $. It will substitute the python variable.

!rm -r $name

You may need to use $name\.txt or {name}.txt in some cases.

korakot
  • 37,818
  • 16
  • 123
  • 144
  • This does not work with the following command `!git clone https://$GITHUB_AUTH@github.com/$user/my-repo.git`, where `user` is a Python variable and `$GITHUB_AUTH` corresponds to `os.environ['GITHUB_AUTH']`, which is correctly replaced with the corresponding value in the command above, as opposed to the variable `user`, which is replaced with an empty string. – nbro Oct 15 '19 at 13:42
  • 11
    @nbro I would recommend using quotes in your shell command: `!git clone "https://"$GITHUB_AUTH"@github.com/"$user"/my-repo.git"`. I use similar command for managing git and files from buckets and it works perfectly for me :) – Jeremy Cochoy Dec 26 '19 at 12:14
  • 1
    and you may also consider adding quotes around your $variableName in case it has spaces or other chars which will break the command. e.g. `!rm -r "$name"` – user566245 Nov 13 '20 at 18:53
10

Use {}.

myvar = "/test"
!cd {myvar}

According to https://colab.research.google.com/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/01.05-IPython-And-Shell-Commands.ipynb#scrollTo=q-zpo3vGM5Jv

ZygD
  • 22,092
  • 39
  • 79
  • 102
AgathoSAreS
  • 378
  • 3
  • 7
  • Thanks for edit, now it looks even nicer. Btw. the #scrollTo is broken. You have to scroll yourself to find the source. – AgathoSAreS Dec 20 '21 at 14:36