chopper draw lion4
chopper draw lion4

Reputation: 13507

Terminal: How do I pass arguments into an alias?

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?

Upvotes: 1

Views: 1702

Answers (2)

anubhava
anubhava

Reputation: 786081

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)";
}

Upvotes: 5

fredtantini
fredtantini

Reputation: 16586

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.

Upvotes: 2

Related Questions