2

I'm writing a startup.sh script to be ran when a docker container is created.

#!/bin/bash
python manage.py runserver
python manage.py makemigrations accounts
python manage.py migrate
python manage.py check_permissions    
python manage.py cities --import=country --force

*python manage.py shell | from cities.models import * Country.objects.all().exclude(name='United States").delete()*

python manage.py cities --import=cities
python manage.py cities --import=postal_code

I am guessing the line in question is incorrect, what would be the correct way to do this in a bash script?

3
  • Also open to any suggestions of a better way to do this Commented Jan 4, 2017 at 21:09
  • In terms of trying to get a better feel for how pipelines work in bash -- foo | bar connects the stdout of foo to the stdin of bar. Thus, the command you proposed sends the output of python manage.py shell to the input of a command named from, with its second argument cities.models, &c. Commented Jan 4, 2017 at 21:13
  • You could perhaps do this the other way: printf '%s\n' 'from cities.models import *' 'Country.objects.all().exclude(name="United States").delete()' | python manage.py shell -- that way you're sending the output of a printf command that generates your script as the input to the manage.py shell command. Commented Jan 4, 2017 at 21:14

2 Answers 2

3

Use a heredoc:

python manage.py shell <<'EOF'
from cities.models import *
Country.objects.all().exclude(name='United States').delete()
EOF
Sign up to request clarification or add additional context in comments.

1 Comment

I am going to try this.
2

It's not such a good idea to include django code in a shell script file. It's better to either make a python file and put those code in it and do:

python manage.py shell < script.py

Or better, write a django management command. In this way you could track your code in the same project/repo and people got less confused when they see this.

1 Comment

Thumbs-up for the management command suggestion. I actually think I prefer either the management-command approach or the heredoc approach to python manage.py shell <script.py -- in the latter case, you have a script.py that won't run unless invoked in a very specific way, whereas either the heredoc or the management command are provided in a context that makes their invocation obvious.

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.