1# SPDX-License-Identifier: BSD-2-Clause 2 3# RCSid: 4# $Id: safe_eval.sh,v 1.12 2023/10/12 18:46:53 sjg Exp $ 5# 6# @(#) Copyright (c) 2023 Simon J. Gerraty 7# 8# This file is provided in the hope that it will 9# be of use. There is absolutely NO WARRANTY. 10# Permission to copy, redistribute or otherwise 11# use this file is hereby granted provided that 12# the above copyright notice and this notice are 13# left intact. 14# 15# Please send copies of changes and bug-fixes to: 16# sjg@crufty.net 17 18_SAFE_EVAL_SH=: 19 20## 21# safe_set 22# 23# return a safe variable setting 24# any non-alphanumeric chars are replaced with '_' 25# 26safe_set() { 27 ${SED:-sed} 's/[ ]*#.*//;/^[A-Za-z_][A-Za-z0-9_]*=/!d;s;[^A-Za-z0-9_. "$,/=-];_;g' 28} 29 30## 31# safe_eval [file] 32# 33# eval variable assignments only from file 34# taking care to eliminate any shell meta chars 35# 36safe_eval() { 37 eval `cat "$@" | safe_set` 38} 39 40## 41# safe_dot file [...] 42# 43# feed all "file" that exist to safe_eval 44# 45safe_dot() { 46 local ef= f 47 48 for f in "$@" 49 do 50 test -s $f || continue 51 ef="${ef:+$ef }$f" 52 dotted="$dotted $f" 53 done 54 test -z "$ef" && return 1 55 safe_eval $ef 56 return 0 57} 58 59case /$0 in 60*/safe_eval*) 61 case "$1" in 62 dot|eval|set) op=safe_$1; shift; $op "$@";; 63 *) safe_dot "$@";; 64 esac 65 ;; 66esac 67