bash函数中的可选参数


12

我有一个快速创建新的SVN分支的功能,如下所示

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

我用它来快速创建一个新分支,而不必查找并复制粘贴地址和其他内容。但是,对于消息(-m选项),我想使用它,以便如果我提供第三个参数,则将其用作消息,否则将使用“ $ 2的dev分支”的“默认”消息。有人可以解释如何完成吗?

Answers:


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

变量msg设置为$3if $3非空,否则设置为默认值dev branch for $2$msg然后用作的参数-m


3

从bash手册页:

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

在您的情况下,您将使用

$ function svcp(){
  def_msg =“ $ 2的dev分支”
  echo svn copy“ repoaddress / branch / $ 1.0.x”“ repoaddress / branch / dev / $ 2” -m \“ $ {3:-$ def_msg} \”;
}

$ svcp 2令人兴奋的新资料
svn复制repoaddress / branch / 2.0.x repoaddress / branch / dev / exciting_new_stuff -m“令人兴奋的new_stuff的开发分支”

$ svcp 2令人兴奋的新事物“统治世界的秘密秘方”
svn复制repoaddress / branch / 2.0.x repoaddress / branch / dev / exciting_new_stuff -m“世界统治的秘密秘诀”
$

如果您对生成的svn命令感到满意,则可以删除echo命令

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.