Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need to print the value of a Django setting while in a Bash shell.

Basically, the command I'd like to run is python -c 'from django.conf import settings; print settings.MEDIA_ROOT'. I need to be in a certain path and pass DJANGO_SETTINGS_MODULE to it though, so I thought I'd wrap the whole thing inside a bash function that I could call instead, pyt -c [...]

I've used $@ successfully in the past in similar situations, so I was hoping it would help here, too. But it's not working as I've got it set up right now.

function pyt {
    cd $PROJECT_ROOT # set elsewhere, parent dir of my_site
    DJANGO_SETTINGS_MODULE=my_site.settings python $@
    cd $OLDPWD

If I type pyt -c "print 'foo'" to test it, "foo" is not printed. A blank line is. python -c "print 'foo'" prints it correctly, so it's something to do with my function here.

If I put echo $@ inside the function, all the parameters are printed out just fine. The Python interpreter is not started either (it is if I just type pyt), so the -c parameter seems to be having some effect—nothing just gets printed out.

What am I missing?

share|improve this question
up vote 2 down vote accepted

You're misunderstanding how the arguments get passed around.

When you run python -c "print 'foo'" the shell parses it into

  • python
  • -c
  • print 'foo'

so python ends up seeing two arguments.

When you run pyt -c "print 'foo'" the line python $@ gets expanded to (the equivalent of) python -c print 'foo', which gets tokenised as

  • python
  • -c
  • print
  • foo

i.e. python sees three arguments, and will run the command print, with the string foo in sys.argv[1].

What you need to do is use a magic shell token: instead of just $@ use "$@" (it must be double quotes). That tells the shell to keep arguments together; when you run pyt -c "print 'foo'", the line python "$@" gets expanded to (the equivalent of) python -c "print 'foo'".

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .