Reputation: 1012
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!
Upvotes: 0
Views: 330
Reputation: 295687
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.
Upvotes: 2