问题
I have a 3rd party generator that's part of my build process (sbt native packager). It generates a bash script to be used to run my built program.
Problem is I need to use sh (ash), not bash. So the generator cranks out a line like this:
declare -a app_mainclass=("com.mypackage.Go")
sh chokes on this as there is no 'declare' command.
Clever me--I just added these lines:
alias declare=''
alias '-a'=''
This worked on all such declarations except this one--because of the parens. sh apparently has no arrays.
Given that I cannot practically change the generator, what can I do to spoof the sh code to behaving properly? In this case I logically want to eliminate the parens. (If I do this manually in the generated output it works great.)
I was thinking of trying to define a function app_mainclass= () { app_mainclass=$1; }
but sh didn't like that--complained about the (. Not sure if there's a way to include the '=' as part of the function name or not.
Any ideas of a way to trick sh into accepting this generated command (the parens)?
回答1:
I hesitate to suggest it, but you might try a function declaration that uses eval
to execute any assignments produced by a declare
statement. I might verify that the generated declare
statements are "safe" before using this. (For example, that the assigned value doesn't contain any thing that might be executed as arbitrary code by eval
.)
declare () {
array_decl=
for arg; do
# Check if -a is used to declare an array
[ "$arg" = -a ] && array_decl=1
# Ignore non-assignment arguments
expr "$arg" : '.*=.*' || continue
# Split the assignment into separate name and value
IFS='=' read -r name value <<EOF
$arg
EOF
# If it's an array assignment, strip the leading and trailing parentheses
if [ -n "array_decl" ]; then
value=${value#(}
value=${value%)}
fi
# Cross your fingers... I'm assuming `$value` was already quoted, as in your example.
eval "$name=$value"
done
}
来源:https://stackoverflow.com/questions/31065071/bash-to-sh-ash-spoofing