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.
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 .
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}.
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.
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.
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
.
The following option has worked for me:
NAME="par1-par2-par3"
echo $(TMP=${NAME%-*};echo ${TMP##*-})
Output is:
par2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With