【问题标题】:Bash Passing variables to stringBash 将变量传递给字符串
【发布时间】:2020-06-16 13:33:34
【问题描述】:

因此,当我在命令行上运行 pr 命令时,我正在尝试创建一个别名以在特定 URL 中打开浏览器。

function pr() {
  repoName=(basename `git rev-parse --show-toplevel`)
  branchName=(`git rev-parse --abbrev-ref HEAD`)
  $repoName <- printing a-public
  $branchName <- printing acq-248
  open -a "Google Chrome" "https://bitbucket.org/company/$repoName/pull-requests/new?source=$branchName&event_source=branch_list"
}

所以,当我运行 pr 时,我可以看到 $repoName 和 $branchName 具有正确的值,但打开的 url 确实部分解释了它 -> https://bitbucket.org/company/Users/v/projs/a-public/pull-requests/new?source=acq-248&amp;event_source=branch_list

那么,传递这些变量以连接到我要打开的 URL 的正确方法是什么?

【问题讨论】:

  • 如果您对 bash 解决方案感兴趣,为什么要将此问题标记为 zshshshell只有?

标签: bash shell terminal sh zsh


【解决方案1】:

它们都是数组赋值。

repoName=(basename `git rev-parse --show-toplevel`)
branchName=(`git rev-parse --abbrev-ref HEAD`)

如果您想在变量中扩展命令输出,请使用不带反引号但 $( ) 的命令替换

repoName=$(basename $(git rev-parse --show-toplevel))
branchName=$(git rev-parse --abbrev-ref HEAD)

尝试使用 %q 引用 url,以便可以将其作为安全参数传递给 shell。

var="https://bitbucket.org/company/$repoName/pull-requests/new?source=$branchName&event_source=branch_list"

引用它是外壳安全的。

printf -v url '%q' "$var"

现在试试你的命令。

open -a "Google Chrome" "$url"

【讨论】:

  • 你杀了它,tks。我不知道 $() 的事情。工作顺利!
  • 很高兴能帮上忙。
  • 您应该引用内部命令替换并使用小写的变量名。要使变量成为函数的局部变量,请使用 declarelocal 关键字:declare repo=$(basename "$(git rev-parse --show-toplevel)")
  • @Freddy,正确声明变量本地但没有赋值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-28
  • 2017-02-22
  • 1970-01-01
相关资源
最近更新 更多