Remove a character from the end of a variable

BashShell

Bash Problem Overview


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

Bash Solutions


Solution 1 - Bash

Use

target=${1%/}

A reference.

Solution 2 - Bash

Use target=${1%/}

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

Solution 3 - Bash

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

Solution 4 - Bash

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBurntimeView Question on Stackoverflow
Solution 1 - Bashmartin claytonView Answer on Stackoverflow
Solution 2 - BashGregory PakoszView Answer on Stackoverflow
Solution 3 - BashamenzhinskyView Answer on Stackoverflow
Solution 4 - BashJohn P. FisherView Answer on Stackoverflow