-1

In a bash script, I want to extract the 2 last folders of the pwd.

I did this :

value=`pwd`
echo "you are here : $value"
echo "the folder is: ${value##*/}"

To have this :

you are here: /home/user/folder1/folder2
the folder is folder2

Now I want to extract the parent folder (folder1).

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223

3 Answers3

1

Like this, using pre-defined variable PWD:

value="$PWD"
echo "you are here :$value"
echo "the folder is: ${value##*/}"
echo "the parent folder is $(basename "${PWD%/*}")"

You can replace the last line with:

dir="${PWD%/*}"
echo "the parent folder is ${dir##*/}"

The backquote (`) is used in the old-style command substitution, e.g.

foo=`command`

The foo=$(command) syntax is recommended instead. Backslash handling inside $() is less surprising, and $() is easier to nest. See http://mywiki.wooledge.org/BashFAQ/082

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
1

Try this:

value=`pwd`
echo "you are here: $value"
echo "the folder is ${value##*/}"
parent="${value%/*}"
echo "the parent folder is ${parent##*/}"

in order to get this:

you are here: /home/user/folder1/folder2
the folder is folder2
the parent folder is folder1
Tilman Schmidt
  • 193
  • 1
  • 5
  • Whe are now in 2020. The backquote is used in the old-style command substitution. The `foo=$(command)` syntax is recommended instead. Backslash handling inside $() is less surprising, and $() is easier to nest. See http://mywiki.wooledge.org/BashFAQ/082 – Gilles Quénot Jun 21 '20 at 13:28
  • 2
    I know. But that was the OP's choice, not mine. It's better to keep the parts that aren't directly affected by the actual answer as they are so not to confuse the asker. – Tilman Schmidt Jun 21 '20 at 13:34
  • Thanks both of you ! I'm newbie learning it. Better learn the good way to doing it. – Quentin Lesauce Jun 21 '20 at 14:30
0

Here's a solution using regular expressions: If you want to know how the regular expression works I suggest you take a look on this site.

#!/bin/bash
value=$(pwd)
regex='.*\/([a-zA-Z0-9\._]*)\/([a-zA-Z0-9\._]*)$'
echo You are here: $value
echo The folder is: ${value##*/}
[[ $value =~ $regex ]]
echo Parent folder: ${BASH_REMATCH[1]}
Dennishofken
  • 317
  • 2
  • 9