Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash provide default argument if no arguments passed

Tags:

bash

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)?

like image 688
asiniy Avatar asked May 07 '26 20:05

asiniy


2 Answers

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" "$@"
}
like image 172
Hauleth Avatar answered May 11 '26 14:05

Hauleth


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

like image 45
arco444 Avatar answered May 11 '26 14:05

arco444