bash 删除变量末尾的斜线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1848415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 18:45:39  来源:igfitidea点击:

Remove slash from the end of a variable

bashshell

提问by Burntime

the bash auto completion make a / at the end of a directory how i can strip this out?

bash 自动完成在目录末尾创建一个 / 我如何去掉它?

Thanks for hints.

谢谢你的提示。

#!/bin/sh

target=

function backup(){
  date=`date "+%y%m%d_%H%M%S"`
  PWD=`pwd`
  path=$PWD/$target
  tar czf /tmp/$date$target.tar.gz $path
}

backup

回答by martin clayton

Use

target=${1%/}

A reference.

一个参考

回答by Gregory Pakosz

Use target=${1%/}

target=${1%/}

See this the parameter substitution of this bash scripting guidefor more.

有关更多信息,请参阅此bash 脚本指南的参数替换

回答by amenzhinsky

I think better solution to canonize paths is realpath $pathor with -moption if it doesn't exist. This solution automaticaly removes unnecessary slashes and adds pwd

我认为更好的规范路径的解决方案是realpath $path或者-m如果它不存在的话。此解决方案会自动删除不必要的斜杠并添加密码

回答by John P. Fisher

Be careful, bash3 added perl-similar regex to bash. The guide mentioned covers this as well as the official guide at GNU, but not all references do.

小心,bash3 向 bash 添加了与 perl 类似的正则表达式。提到的指南涵盖了这一点以及GNU官方指南,但并非所有参考资料都如此。

What did I do?

我做了什么?

Substitute 2.19/*to be 2.19.

替代2.19/*2.19

Solution

解决方案

VER="2.19/foo-bar"
NEWVER=${VER%/*}