Alex Antonov
Alex Antonov

Reputation: 15226

Bash provide default argument if no arguments passed

I have a program installed which named zeus. It's allow me to run commands like this:

zeus parallel_rspec spec/

Where parallel_rspec is command which is runned by zeus and spec/ is the directory, which is required by parallel_rspec command.

I've made an alias in my .profile:

alias rsp='zeus parallel_rspec'

So, I can run commands like this:

rsp spec/ # => equal to `zeus parallel_rspec spec/`

But spec/ directory is common (95% cases). How can I make my rsp alias pass spec/ folder argument by default (if I'm not passed something another, like spec/blablabla)?

Upvotes: 9

Views: 5502

Answers (2)

arco444
arco444

Reputation: 22881

You should use a function instead:

function rsp {
  [ -z "$1" ] && zeus parallel_rspec spec/ || zeus parallel_rspec "$1"
}

You can add it to your profile or bashrc. If you provide no argument to the function $1 will be empty so it will use /spec as the path, otherwise it will use the argument

Upvotes: 7

Hauleth
Hauleth

Reputation: 23586

Bash has syntax for default value of variable:

${VARNAME:-default}

So in your case you need to use function that looks like:

rsp() { zeus parallel_rspec "${1:-spec/}" }

or if you wanna pass some more options, just in case:

rsp() {
  folder="${1:-spec/}"
  shift 1
  zeus parallel_rspec "$folder" "$@"
}

Upvotes: 20

Related Questions