Use parameter expansion over a parameter expansion in bash.

Hello All,

Could you please do help me here as I would like to perform parameter expansion in shell over a parameter expansion.

Let's say I have following variable.

path="/var/talend/nat/cdc"

Now to get only nat I could do following.

path1="${path%/*}"
path1="${path1##*/}"

Here in this approach I am creating a temporary variable path1 and again performing parameter expansion, how about if I want to perform this in single time without having temporary variable? I have tried it like:

echo "${((${path%/*}))##*/}"

Which is giving me an error. Any help, guidance is appreciated.

Thanks,
R. Singh

1 Like

Hi
try this

basename $(dirname /var/talend/nat/cdc)

--- Post updated at 11:33 ---

basename ${path%/*}

--- Post updated at 11:51 ---

Here is a solution I finded completely not practical but interesting

: ${path%/*}; echo ${_##*/}
1 Like

love things like that

echo $(expr match "$path" '.*/\([^/]*\)/[^/]*')
1 Like

Hi Ravinder...

A fun approach but fully 'dash' compliant:

Last login: Tue Jan 28 14:17:35 on ttys000
AMIGA:amiga~> dash
AMIGA:\u\w> path="/var/talend/nat/cdc"
AMIGA:\u\w> path=${path%/*};path=${path##*/}
AMIGA:\u\w> printf "%s\n" "${path}"     
nat
AMIGA:\u\w> exit
AMIGA:amiga~> _
2 Likes

Hi @wisecracker
I think this is the same option. Change a little and it will be quite practical

: ${path%/*} && echo ${_##*/}

but it's just not convenient to pass this parameter on

1 Like

Hi nez...
I do not like 'eval' but here goes and is also 'dash' compliant...

Last login: Tue Jan 28 14:17:35 on ttys000
AMIGA:amiga~> dash
AMIGA:\u\w> path="/var/talend/nat/cdc"
AMIGA:\u\w> path=$( eval path=${path%/*} && echo ${_##*/} )
AMIGA:\u\w> echo "${path}"
nat
AMIGA:\u\w> exit
AMIGA:amiga~> _

This is how it will be without "eval"

$( : ${path%/*} && echo ${_##*/} )

that would be without "echo" :slight_smile:

1 Like

It's interesting that on "zsh" it works

2 Likes

Really interesting. By definition it is a variable modifier that means the LHS must be a variable. Nesting can only be attempted on the RHS that is a string.
Apparently in zsh the LHS can be a string that means it is a full functional operator.

1 Like