Bash:${$(mycommand)%suffix} 不适用于 mycommand 输出的 trim 后缀
Bash: ${$(mycommand)%suffix} doesn't work to trim suffix from mycommand output
我正在尝试将目录更改为我的 git 存储库的远程位置。我正在使用命令:
cd ${$(git remote get-url origin)%.git}
命令无效:
bash: ${$(git remote get-url origin)%.git}: bad substitution
我不明白为什么这是不正确的。是因为 $()
而不是使用变量名吗?如果是,为什么?我怎样才能正确地做到这一点?
您不能在 bash
中使用嵌套字符串替换。
相反,您可以使用这个单行代码:
cd $(git remote get-url origin | sed 's/\.git$//')
您不能在参数扩展中使用命令替换并删除子字符串。你需要两步:
tmp=$(git remote get-url origin)
cd "${tmp%.git}"
这将消除错误的替换。
Parameter expansion itself operates on a shell parameter(包括 shell 由名称、位置参数等引用的变量)。因此,如果您使用 %.git
从右侧删除 .git
,则它必须包含在某个变量中,例如tmp
以上,则参数扩展按预期工作。
我正在尝试将目录更改为我的 git 存储库的远程位置。我正在使用命令:
cd ${$(git remote get-url origin)%.git}
命令无效:
bash: ${$(git remote get-url origin)%.git}: bad substitution
我不明白为什么这是不正确的。是因为 $()
而不是使用变量名吗?如果是,为什么?我怎样才能正确地做到这一点?
您不能在 bash
中使用嵌套字符串替换。
相反,您可以使用这个单行代码:
cd $(git remote get-url origin | sed 's/\.git$//')
您不能在参数扩展中使用命令替换并删除子字符串。你需要两步:
tmp=$(git remote get-url origin)
cd "${tmp%.git}"
这将消除错误的替换。
Parameter expansion itself operates on a shell parameter(包括 shell 由名称、位置参数等引用的变量)。因此,如果您使用 %.git
从右侧删除 .git
,则它必须包含在某个变量中,例如tmp
以上,则参数扩展按预期工作。