I'd like to pass input from a shell command over to a python script in an alias that uses a shell command.


import sys

the alias

alias foo='echo $(python test.py $1)'

since $ python cd_alias_test.py hello would print all the args: ['test.py', 'hello'] I'd expect this alias to do the same. However its stdout is

['test.py'] hello

Which means that the input string is being passed to stdin and not the script's arguments.

How I achieve the intended effect?


2 Answers 2

alias test='echo $(python test.py $1)'

$1 is not defined in an alias, aliases aren't shell functions; they're just text replacement; so your test hello gets expanded to echo $(python test.py ) hello, which gets expanded to echo ['test.py'] hello.

If you want a shell function, write one! (and don't call your function or alias test, that name is already reserved for the logical evaluation thing in your shell).

function foo() { echo $(python test.py $1) }
foo hello

But one really has to wonder: Why not simply make test.py executable (e.g. chmod 755 test.py) and include the #!/usr/bin/env python3 first line in it? Then you can just run it directly:

./test.py hello darkness my old friend
  • Functionally speaking echo $(thing) could/should just be thing -- otherwise there's a risk of echo interpreting the output of thing as switches it should care about, e.g. echo $(printf "%s" "-n hello") ; echo world
    – bxm
    Jun 23 at 10:50
  • @bxm that might be the intention here! Jun 23 at 11:07
  • I understand how functions are more appropriate for this task, but I'm still a little confused as to how arguments like $1 are not defined in an alias. For instance if I have alias foo='python cd_alias_test.py $1', then the output for $ foo hello will be ['cd_alias_test.py', 'hello'] Jun 23 at 18:21
  • they're simply... not defined. There's nothing setting up a variable called $1, because an alias gets expanded to its value as if you just typed that in. So, your foo hello looks like you typed in python cd_alias_test.py $1 hello and that gets expanded to python cd_alias_test.py hello before execution. There's really no magic here. Just your assumption about what an alias does being a bit wrong, it seems! An alias doesn't take "arguments". An alias simply doesn't "exist" as programming construct: it gets replaced by its value before anything gets defined, expanded… Jun 23 at 18:23

Your question is confusingly worded, but I seems you just want to execute an alias passing a parameter to your script.

I think this is what you want.

alias runtest='python test.py'

As otherwise mentioned, shell functions can be preferable to aliases -- allowing for less trivial arg handling.

So in this example:

function runtest() { python test.py "$1" ; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.