0

I wrote a shell function, intended to be compatible with both zsh and bash:

py () { python -c 'print($1)'; }

but when i use py hello, I get an error from the Python interpreter:

➜  ~  py hello
  File "<string>", line 1
    print($1)
          ^
SyntaxError: invalid syntax

What am I doing wrong? Thanks!

0

1 Answer 1

2

Don't use string substitution at all -- that way lies (a cousin of) Bobby Tables. Instead, pass arguments out-of-band:

py() { python -c 'import sys; print sys.argv[1]' "$@"; }
py hello

To demonstrate why the other approach is dangerous:

py() { python -c "print('${1}')"; }
py "hello' + str(__import__('os').system('touch /tmp/broke-your-security')) + '"

When run, this code creates a file /tmp/broke-your-security. Consider what would happen if that command instead involved rm -rf, or curl | sh to pull down a rootkit.

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

2 Comments

hi! i am not using this function in production, just for personal use :)
@sindhus, sure, but you'll eventually be writing production code, no? Better to be in good habits before it matters. :)

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.