Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can ${var} parameter expansion expressions be nested in bash?

Tags:

bash

What I have is this:

progname=${0%.*}
progname=${progname##*/}

Can this be nested (or not) into one line, i.e. a single expression?

I'm trying to strip the path and extension off of a script name so that only the base name is left. The above two lines work fine. My 'C' nature is simply driving me to obfuscate these even more.

like image 217
user71918 Avatar asked May 27 '09 18:05

user71918


People also ask

What is parameter expansion in bash?

Bash uses the value formed by expanding the rest of parameter as the new parameter ; this is then expanded and that value is used in the rest of the expansion, rather than the expansion of the original parameter . This is known as indirect expansion .

How do you expand a variable in bash?

Parameter expansion comes in many forms in bash, the simplest is just a dollar sign followed by a name, eg $a. This form merely substitutes the value of the variable in place of the parameter expansion expression. The variable name can also optionally be surround by braces, eg ${a}.

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.


3 Answers

Bash supports indirect expansion:

$ FOO_BAR="foobar"
$ foo=FOO
$ foobar=${foo}_BAR
$ echo ${foobar}
FOO_BAR
$ echo ${!foobar}
foobar

This should support the nesting you are looking for.

like image 149
user1956358 Avatar answered Oct 20 '22 23:10

user1956358


If by nest, you mean something like this:

#!/bin/bash

export HELLO="HELLO"
export HELLOWORLD="Hello, world!"

echo ${${HELLO}WORLD}

Then no, you can't nest ${var} expressions. The bash syntax expander won't understand it.

However, if I understand your problem right, you might look at using the basename command - it strips the path from a given filename, and if given the extension, will strip that also. For example, running basename /some/path/to/script.sh .sh will return script.

like image 62
Tim Avatar answered Oct 20 '22 21:10

Tim


The following option has worked for me:

NAME="par1-par2-par3"
echo $(TMP=${NAME%-*};echo ${TMP##*-})

Output is:

par2
like image 20
luferbraho Avatar answered Oct 20 '22 22:10

luferbraho