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