42

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?

2 Answers 2

76

Try $. It will substitute the python variable.

!rm -r $name

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

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

3 Comments

This does not work with the following command !git clone https://[email protected]/$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 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 :)
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"
17

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

1 Comment

Thanks for edit, now it looks even nicer. Btw. the #scrollTo is broken. You have to scroll yourself to find the source.

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.