Reputation: 26355
I have the following bash script (I execute it using msysgit). The file is named git-open
:
#!/usr/bin/env bash
tempfile=`mktemp` || exit 1
git show $1 > $tempfile
notepad++ -multiInst -notabbar -nosession -noPlugin $tempfile
rm $tempfile
I invoke it through git like so:
git open master:Applications/Survey/Source/Controller/SurveyManager.cpp
Before I open this in notepad++, I want it to append the extension to the temporary file so that the editor automatically applies the correct syntax highlighting. If there is no extension specified, then mktemp shouldn't have to add an extension.
How can I modify my script above to work like this? I have very little experience with linux scripting, so I'm not sure how to implement a regex for this (assuming regex is necessary).
Upvotes: 0
Views: 109
Reputation: 189397
You can pass mktemp
a template for your file name.
tempfile=$(mktemp -t git-open.XXXXXXXX.${1##*.}) || exit 1
Upvotes: 2
Reputation: 76276
Regular expressions are overkill for this. Glob patterns in parameter expansion with prefix removal is completely sufficient.
tempfile=`mktemp`.${1##*.}
The ${1##*.}
means "expand $1
but remove longest prefix that matches the globbing pattern *.
. *
matches everything and .
matches itself, so this removes everything up to and including last .
. What remains is the extension.
Instead of the ##
you can also use #
for shortest prefix, %
for shortest suffix and %%
for longest prefix.
Ok, you probably want to handle cases where there is no extension. That can be done with help of case
and more glob patterns:
case ${1##*/} in
*.*) suffix=${1##*.};;
*) suffix='';;
esac
tempfile=`mktemp`$suffix
This will take the filename without leading directories, test whether it contains .
and use the suffix only if it does. Or you can compare the expansion with the original as devnull suggests.
Upvotes: 1