Do not use eval ! This has a great risk of introducing arbitrary code execution.
BashFAQ-50 - I'm trying to put a command in a variable, but complex cases always fail.
Put it in an array and expand all the words with double quotes "${arr[@]}" to prevent IFS from splitting words due to splitting the Word .
cmdArgs=() cmdArgs=('date' '+%H:%M:%S')
and look at the contents of the array inside. declare -p allows you to see the contents of an array inside with each command parameter in separate indexes. If one such argument contains spaces, quotation marks when added to an array will prevent it from breaking due to word breaking.
declare -p cmdArgs declare -a cmdArgs='([0]="date" [1]="+%H:%M:%S")'
and execute commands like
"${cmdArgs[@]}" 23:15:18
(or) generally use the bash function to run the command,
cmd() { date '+%H:%M:%S' }
and call the function just
cmd
POSIX sh has no arrays, so the closest thing you can get is to create a list of elements in positional parameters. Here is the POSIX sh way to run the mailer
# POSIX sh # Usage: sendto subject address [address ...] sendto() { subject=$1 shift first=1 for addr; do if [ "$first" = 1 ]; then set --; first=0; fi set -- "$@" --recipient="$addr" done if [ "$first" = 1 ]; then echo "usage: sendto subject address [address ...]" return 1 fi MailTool --subject="$subject" "$@" }
Note that this approach can only handle simple commands without redirects. It cannot handle redirects, pipelines, for / while loops, if statements, etc.
Inian May 18 '17 at 19:00 2017-05-18 19:00
source share