Home > Software design >  what happens in bash 'echo ${full_path##/*}'
what happens in bash 'echo ${full_path##/*}'

Time:09-16

I found this easy filename printing on the internet. But I cant find explanation what does these ##*/ mean? It doesnt look like regex. More over, could it be used with result of readlink in one line?

CodePudding user response:

From Manipulating String, Advanced Bash-Scripting Guide

${string##substring}

Deletes longest match of substring from front of $string.


So in your case, the * in the substring indicates: match everything.

The command echo ${full_path##/*} will:

Print $full_path unless it starts with a forward slash (/), in that case an empty string will be shown


Example cases;

$ test_1='/foo/bar'
$ test_2='foo/bar'
$
$ echo "${test_1##/*}"

$ echo "${test_2##/*}"
foo/bar
$

Regarding your second question:

More over, could it be used with result of readlink in one line?

Please take a look at Can command substitution be nested in variable substitution?.

If you're using I'd recommend keeping it simple, by assigning the result of readlink to a variable, then using the regular variable substitution to get the desired output. Linking both actions could be done using the && syntax.

An one-liner could look something like:

tmp="$(readlink -f file_a)" && echo "${tmp##/*}"
  •  Tags:  
  • bash
  • Related