Optional parameters in bash function

19,914

Solution 1

function svcp() { 
    msg=${3:-dev branch for $2}
    svn copy "repoaddress/branch/$1.0.x" "repoaddress/branch/dev/$2" -m "$msg";
}

the variable msg is set to $3 if $3 is non-empty, otherwise it is set to the default value of dev branch for $2. $msg is then used as the argument for -m.

Solution 2

from the bash man page:

 ${parameter:-word}
          Use Default Values.  If parameter is unset or null, the expansion of word is substituted.  Otherwise, the value of parameter is substituted.

in your case, you would use

$ function svcp() {
  def_msg="dev branch for $2"
  echo svn copy "repoaddress/branch/$1.0.x" "repoaddress/branch/dev/$2" -m \"${3:-$def_msg}\";
}

$ svcp 2 exciting_new_stuff
svn copy repoaddress/branch/2.0.x repoaddress/branch/dev/exciting_new_stuff -m "dev branch for exciting_new_stuff"

$ svcp 2 exciting_new_stuff "secret recipe for world domination"
svn copy repoaddress/branch/2.0.x repoaddress/branch/dev/exciting_new_stuff -m "secret recipe for world domination"
$

you can remove the echo command if you are satisfied with the svn commands that are generated

Share:
19,914

Related videos on Youtube

Madden
Author by

Madden

Updated on September 18, 2022

Comments

  • Madden
    Madden over 1 year

    I have a function for quickly making a new SVN branch which looks like so

    function svcp() { svn copy "repoaddress/branch/$1.0.x" "repoaddress/branch/dev/$2" -m "dev branch for $2"; }
    

    Which I use to quickly make a new branch without having to look up and copy paste the addresses and some other stuff. However for the message (-m option), I'd like to have it so that if I provide a third parameter then that is used as the message, otherwise the 'default' message of "dev branch for $2" is used. Can someone explain how this is done?