I'm trying to write a bash script function that will either execute a command or echo the command to the console depending on a variable test.
Code:
#!/bin/bash
execD () {
if [[ "$Debug" == "On" ]]
then
echo "$*"
else
$*
fi
}
Debug='On'
execD "echo \"Debug = $Debug\" | wc -w"
Debug='Off'
execD "echo \"Debug = $Debug\" | wc -w"
Output of above bash script.
Code:
echo "Debug = On" | wc -w
"Debug = Off" | wc -w
What I was intending the second line of output to be is the number 3, but instead bash assumes the pipe and wordcount command are part of the text to be echoed. I've found that if I replace the $* in the else section with /bin/bash -c "$*" then it works. It seems like a less elegant and less efficient way to do this however. Is there a way to do this without shelling out to another bash environment?
Thanks in advance,
Jason