I have a script, that does nothing useful but execute the positional arguments. (I'm aware of the security risks, and the script does not make anything useful because it's a minimal working example.)
$ cat script
> #!/usr/bin/env bash
>
> eval "${*}"
$ cat "docu ment"
> Lorem ipsum dolor sit amet
What I would like to do is call the script with ./script cat "docu ment"
, or ./script cat docu\ ment
, but the quotes or the escape character vanishes and the script will try cat docu ment
, which doesn't work. How would I fix the quoting in such a case?
EDIT: What I really want to do, is invoke a command as many times until it returns a successful exit code, or it tried n times. My script looks like this:
#!/usr/bin/env bash
# Try command several times, until it reports success (exit code 0)
# or I give up (tried n times)
tryMax=10
try=1
# Do until loop in bash
while
eval "${@}"
exitcode="${?}"
[[ "${exitcode}" -ne 0 && "${try}" -lt "${tryMax}" ]]
do (( try++ ))
done
if [[ "${exitcode}" -ne 0 ]]; then
echo -n "I tried hard, but did not manage to make this work. The exit code "
echo "of the last iteration of this command was: ${exitcode}."
exit "${exitcode}"
fi
./script cat "\"docu ment\""
will work in this case, but are you really sure that's what you want to do? It's really not viable to pass evaluable scripts in that way, by hand anyway."$@"
would do the same for your toy example - what is your real use case? What sort of commands do you expect to be provided? – Michael Homer May 05 '19 at 08:29@
instead of*
. But better still, don't useeval
. It's far more likely there's a safer way of doing whatever it is you're trying to do. Show us that, and you'll get a safe alternative. – Chris Davies May 05 '19 at 08:29