I’m new to shell programming. I intend to get directory name after zip file was extracted. The print statement of it is
$test.sh helloworld.zip
helloworld
Let’s take a look at test.sh:
#! /bin/sh
length=echo `expr index "$1" .zip`
a=$1
echo $(a:0:length}
However I got the Bad substitution error from the compiler.
And when I mention about ‘shell’.I just talking about shell for I don’t know the difference between bash or the others.I just using Ubuntu 10.04 and using the terminal. (I am using bash.)
If your shell is a sufficiently recent version of
bash, that parameter expansion notation should work.In many other shells, it will not work, and a
bad substitutionerror is the way the shell says ‘You asked for a parameter substitution but it does not make sense to me’.Also, given the script:
The second line exports variable
lengthwith valueechofor the command that is generated by runningexpr index "$1" .zip. It does not assign tolength. That should be just:where the
${1:?}notation generates an error if$1is not set (if the script is invoked with no arguments).The last line should be:
Note that if
$1holdsfilename.zip, the output ofexpr index $1 .zipis 2, because the letteriappears at index 2 infilename.zip. If the intention is to get the base name of the file without the.zipextension, then the classic way to do it is:and the more modern way is:
There is a difference; if the name is
/path/to/filename.zip, the classic output isfilenameand the modern one is/path/to/filename. You can get the classic output with:Or, in the classic version, you can get the path with:
If the file names can contain spaces, you need to think about using double quotes, especially in the invocations of
basenameanddirname.