2

I'm encountering the following problem:

I have this simple script, called test.sh:

#!/bin/bash

function hello() {
    echo "hello world"
}
hello

when I run it from shell, I got the expected result:

$ ./test2.sh
hello world

However, when I try to run it from Python (2.7.?) I get the following:

>>> import commands
>>> cmd="./test2.sh"
>>> commands.getoutput(cmd)
'./test2.sh: 3: ./test2.sh: Syntax error: "(" unexpected'

I believe it somehow runs the script from "sh" rather than bash. I think so because when I run it with sh I get the same error message:

$ sh ./test2.sh
./test2.sh: 3: ./test2.sh: Syntax error: "(" unexpected

In addition, when I run the command with preceding "bash" from python, it works:

>>> cmd="bash ./test2.sh"
>>> commands.getoutput(cmd)
'hello world'

My question is: Why does python choose to run the script with sh instead of bash though I added the #!/bin/bash line at the beginning of the script? How can I make it right (I don't want to use preceding 'bash' in python since my script is being run from python by distant machines which I cant control).

Thanks!

5
  • Uhm, your shebang looks all wrong. #~/bin/bash, this isn't even a shebang but a simple comment. It should be #!/bin/bash. Commented Mar 25, 2013 at 8:46
  • Sorry. Was just a typo Commented Mar 25, 2013 at 8:49
  • 1
    It works unaltered on my Ubuntu 12.10 32-bit. May be something with your default environment that is causing sh to be used instead of bash. Commented Mar 25, 2013 at 9:03
  • try os.system() it works Commented Mar 25, 2013 at 9:04
  • Oh I see, that's very strange then. What distribution are you using there? Commented Mar 25, 2013 at 9:12

1 Answer 1

3

There seems to be some other problem - the shbang and commands.getoutput should work properly as you show here. Change the shell script to just:

#!/bin/bash
sleep 100

and run the app again. Check with ps f what's the actual process tree. It's true that getoutput calls sh -c ..., but this shouldn't change which shell executes the script itself.

From a minimal test as described in the question, I see the following process tree:

11500 pts/5    Ss     0:00 zsh
15983 pts/5    S+     0:00  \_ python2 ./c.py
15984 pts/5    S+     0:00      \_ sh -c { ./c.sh; } 2>&1
15985 pts/5    S+     0:00          \_ /bin/bash ./c.sh
15986 pts/5    S+     0:00              \_ sleep 100

So in isolation, this works as expected - python calls sh -c { ./c.sh; } which is executed by the shell specified in the first line (bash).

Make sure you're executing the right script - since you're using ./test2.sh, double-check you're in the right directory and executing the right file. (Does print open('./test2.sh').read() return what you expect?)

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.