0

I have the following issue:

I have multiple bash aliases for a python script: The python script is using arg-parse with two arugemnts, one is optional.

testing.py -i value1
testing.py -i value1 -e value2

alias test1=' ./testing.py -i $1' 

This works as expected

alias test2=' ./testing.py -i $1 -e $2'

This doesn't work!

ultimately, would like to do this from the command line:

test2 value1 value2

I've searched bash functions, not entirely sure if it will solve my problem. I've tried numerous ways to escape, qoute, hack around it, rearrange.. etc.. no dice

It would be very helpful to be able to pass the second default argument in bash $2 to the -e argparse option for the python script.

Any help would be greatly appreciated..

Sincerely,

Thanks!

Vedang Mehta
  • 2,214
  • 9
  • 22
  • Your use of single quotes (`'`) doesn't translate the `$1` and `$2` as you'd like. Try using double-quotes (`"`) instead. Further, those argument tokens are for function arguments, which means you'll want a bash function, not an alias – inspectorG4dget May 25 '16 at 14:28
  • I've tried the following: alias test2='./testing.py -i $1' That does work. .it passes the first argument regardless of qoutes. However, alias test2='./testing.py -i "$1" ' works as well.. The problem occurs when trying to pass two arguments.. from bash alias to the python script. – ArmBarFromGod May 25 '16 at 14:34
  • 1
    Aliases don't process arguments. You need to use functions. – Barmar May 25 '16 at 14:36
  • @ArmBarFromGod, `alias test2='./testing.py -i $1'` doesn't work for the reason you may think it does. The `$1` is empty, but then the content that follows the alias is your original arguments. – Charles Duffy May 25 '16 at 15:02

2 Answers2

0

Aliases are simple prefix expansion. They don't know what their arguments are and can't run conditional logic.

test1() { ./testing.py -i "$1"; }

test2() { ./testing.py -i "$1" -e "$2"; }

...or, better, a single function that handles both cases:

testfunc() { ./testing.py ${1+ -i "$1"} ${2+ -e "$2"}; }
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • awesome. I understand the function. How do I call this function from bash? I assume I can add this function in my .bashrc ? – ArmBarFromGod May 25 '16 at 14:40
  • @ArmBarFromGod, just call it as `testfunc arg1 arg2`, or `testfunc arg1` if that's all you want. And yes, you can put it in your `~/.bashrc`. – Charles Duffy May 25 '16 at 14:40
0

You can't use variables in aliases

(or more precisely you can, but not as you want to)

test1 value1

translates to

./testing.py -i value1

but

test2 value1 value2

translates to

./testing.py -i -e value1 value2

since $1 and $2 are empty strings (most probably).

Use function

Easy solution is to create bash function

test2() {
    ./testing.py -i "$1" -e "$2"
}
pacholik
  • 8,607
  • 9
  • 43
  • 55