139

Bash auto completion appends a / at the end of a directory name. How I can strip this off from a positional parameter?

#!/bin/sh

target=$1

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

backup
0

4 Answers 4

250

Use

target=${1%/}

A reference.

4
  • 9
    And it is POSIX, so is pretty much portable.
    – go2null
    Commented Nov 9, 2015 at 4:13
  • 3
    See Gilles answer for a simple way to strip multiple trailing '/'s while keeping root (/) safe: case $x in *[!/]*/) x=${x%"${x##*[!/]}"};; esac
    – go2null
    Commented Nov 9, 2015 at 4:41
  • 1
    and if you had to use this with a variable, e.g. DIR, then it'd be target=${DIR%/}
    – Brad Parks
    Commented Oct 4, 2018 at 11:23
  • 1
    Another good direct reference. Commented Jun 30 at 13:50
23

Use target=${1%/}

See this the parameter substitution of this bash scripting guide for more.

15

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

5
  • realpath is not likely to be very portable: unix.stackexchange.com/questions/101080/…
    – Matthew
    Commented Jul 10, 2014 at 21:23
  • realpath is a part of GNU coreutils which is de facto in linux distribution and in this case users may have installed different external packages which can break the portability Commented Jul 11, 2014 at 8:46
  • 2
    Not every distro includes realpath. For instance, I'm running Linux Mint 17 (which is Ubuntu based) and it doesn't have it by default. It's in the repos, but it's not installed automatically. That's what the link I posted was discussing.
    – Matthew
    Commented Jul 11, 2014 at 13:30
  • Good solution for the specified use-case although the answer marked as correct is the best for the title and most generic. For me I wanted to remove the trailing slash from a URL so this would not have worked. Regarding your suggestion here, what I have found from experience is that readlink -f is a little more portable than realpath. For additonal/alternative options: linux.die.net/man/1/readlink
    – flungo
    Commented Sep 5, 2015 at 10:12
  • 2
    This worked for me: target=$(realpath -L --relative-base . $1)
    – Mattia72
    Commented Jan 11, 2017 at 11:45
3

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.

What did I do?

Substitute 2.19/* to be 2.19.

Solution

VER="2.19/foo-bar"
NEWVER=${VER%/*}
1
  • Does not work, slash is still there (at the end of variable, which your example does not have). Commented Mar 5, 2018 at 9:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.