Shell Script Explanation

Hello,
I have seen this script on this site. I understand most of it. However I am a bit stuck on the part in red. It appears to be expanding

for file in *.zip
do
 zipdir=${file%.*}
 mkdir $zipdir || echo "unable to create $zipdir"
 cp $file $zipdir || echo "unable to copy $file"
done

Your help is well appreciated.

Kind Regards,
jaysunn

${var%Pattern}, ${var%%Pattern} ${var%Pattern} Remove from $var the shortest part of $Pattern that matches the back end of $var. 
${var%%Pattern} Remove from $var the longest part of $Pattern that matches the back end of $var. 
1 Like

Its called KSH Variable substitution. There are a lot of things that you can do with it. Some of the most common uses are to strip out file extensions, get directory/file names from paths etc.

> path=/home/test/data/xyz.zip
> file=${path##*/}     # Strip out everything from the left of 'path' till the last '/'
> dir=${path%/*}        # Strip out the file name
> filename=${file%.*}
> fileext=${file##*.}
> echo $dir, $file, $filename, $fileext
/home/test/data, xyz.zip, xyz, zip

1 Like
# var=myfile.zip.zip2
 
# echo ${var%.*}      # cut only first matched .* pattern from end  of string so take shortest
myfile.zip
# echo ${var%%.*}   # cut longest matched .* pattern from end of string
myfile
# var=myfile.zip.zip2
 
# echo ${var#*.}      # cut shortest matched *. pattern from beginning of string
zip.zip2
# echo ${var##*.}    # cut longest matched *. pattern from beginning of string
zip2

Regards
ygemici