0

In a directory which is added to my $PATH I have the following file:

filename="$1" day="$2" month="$3"
ruby -r "./SomeClass.rb" -e 'SomeClass.run($filename, $day, $month)'

Suppose this file is called someclass. When I type someclass into terminal my system recognizes it as a valid command and runs the corresponding Ruby file correctly. But the arguments are not being passed in. How do I pass arguments into an alias?

chopper draw lion4
  • 12,401
  • 13
  • 53
  • 100

2 Answers2

4

How do I pass arguments into an alias?

Don't use an alias, better to declare a function for this. You can pass arguments and do other stuff easily inside a bash function:

someclass() {
   # make sure enough arguments are passed in
   # echo "$1 - $2 - $3";
   filename="$1"; day="$2"; month="$3";
   ruby -r "./SomeClass.rb" -e "SomeClass.run($filename, $day, $month)";
}
anishsane
  • 20,270
  • 5
  • 40
  • 73
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • @anishsane: Thanks for making that important quote change, I did a bad copy/paste from question. – anubhava Dec 19 '14 at 10:25
  • How are you declaring a function? Is this a scripting language? Or does bash have this kind of functionality built into itself? – chopper draw lion4 Dec 19 '14 at 10:28
  • This is totally supported in BASH itself. You can place this code in your `~/.bashrc` and then function becomes available anywhere. – anubhava Dec 19 '14 at 10:32
1

You are using single quote. Change them to double:

ruby -r "./SomeClass.rb" -e "SomeClass.run($filename, $day, $month)"

No expansion are done within single quotes. From bash manual:

3.1.2.2 Single Quotes

Enclosing characters in single quotes (‘'’) preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.

3.1.2.3 Double Quotes

Enclosing characters in double quotes (‘"’) preserves the literal value of all characters within the quotes, with the exception of ‘$’, ‘`’, ‘\’, and, when history expansion is enabled, ‘!’. The characters ‘$’ and ‘`’ retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters: ‘$’, ‘`’, ‘"’, ‘\’, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ‘!’ appearing in double quotes is escaped using a backslash. The backslash preceding the ‘!’ is not removed.

A useful page on quotes I am using is on grymoire.

Regarding the title of the question, check this question (Alias with variable in bash) and its answer: you can't and have to use functions.

Community
  • 1
  • 1
fredtantini
  • 15,966
  • 8
  • 49
  • 55