Skip to content

Commit a5a920f

Browse files
author
Giles Westwood
committed
tmp functions
1 parent 5144035 commit a5a920f

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

lib/tmp.sh

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
sk-tmp-userdir(){
2+
local age='' create=1 id=${FUNCNAME[1]:-sk-tmp} base=/var/tmp remove=0
3+
sk_help "Usage: $FUNCNAME create a tmp dir ($base/$id.$USER)
4+
-r | --remove) remove tmp dir
5+
-a | --age) cleanup before create if older than X days
6+
-i | --id) unique id to pass in default is the calling function name
7+
-b | --base) base dir to use ($base) which lasts between reboots
8+
" "$@" && return 1
9+
10+
while :
11+
do
12+
case ${1-default} in
13+
-r | --remove) remove=1 ; shift ;;
14+
-a | --age) age=$2 ; shift 2 ;;
15+
-i | --id) id=$2 ; shift 2 ;;
16+
-b | --base) age=base ; shift 2 ;;
17+
--) shift ; break ;;
18+
-*) echo "WARN: Unknown option (ignored): $1" >&2 ; shift ;;
19+
*) break ;;
20+
esac
21+
done
22+
23+
dir="${base}/${id}.${USER}"
24+
25+
if [[ -d "$dir" ]];then
26+
# basic protection against different user creating the tmpdir
27+
if [[ ! "$(sk-file-stat-user "$dir")" == "$USER" ]];then
28+
sk-logger-args-stdout "CRITICAL: $dir not owned by $USER"
29+
return 1
30+
fi
31+
# cleanup dir if it's older than a certain age
32+
if [[ ! -z "$age" ]];then
33+
find $dir -mtime +$age | xargs rm -rf || true
34+
fi
35+
fi
36+
37+
if [[ ! -d "$dir" ]] && [[ "$create" -eq 1 ]];then
38+
mkdir -p $dir
39+
fi
40+
41+
if [[ -d "$dir" ]] && [[ "$remove" -eq 1 ]];then
42+
rmdir $dir
43+
fi
44+
45+
echo $dir
46+
47+
}
48+
49+
sk-tmp-test(){
50+
sk-tmp
51+
}

0 commit comments

Comments
 (0)