Burntime
Burntime

Reputation: 2344

Remove a character from the end of a variable

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

Upvotes: 139

Views: 71837

Answers (4)

martin clayton
martin clayton

Reputation: 78105

Use

target=${1%/}

A reference.

Upvotes: 249

John P. Fisher
John P. Fisher

Reputation: 269

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%/*}

Upvotes: 3

amenzhinsky
amenzhinsky

Reputation: 992

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

Upvotes: 16

Gregory Pakosz
Gregory Pakosz

Reputation: 70204

Use target=${1%/}

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

Upvotes: 23

Related Questions