My script has a function do_command()
that prints a command and then executes it. I want to put my commands in a bash array of strings, and then print _ execute them with this function. But when I try this with an if statement it fails. This is the script:
#!/bin/bash
do_command () {
echo "$@";
$@;
}
comms=( "wget -O test http://speedtest.ftp.otenet.gr/files/test100k.db" # just a download test
"/bin/bash -c 'if [ -f test ]; then mv test test.old; fi'" # replace previous test
);
for comm in "${comms[@]}"; do do_command "$comm"; done
I have tried different combinations of single + double quotes, putting the bare if-statement there or as an argument of /bin/bash
, but have not yet found a way to do it. With this particular combination, the output from the last line is:
/bin/bash -c 'if [ -f test ]; then mv test test.old; fi'
[: -c: line 1: unexpected EOF while looking for matching `''
[: -c: line 2: syntax error: unexpected end of file
But if I copy and paste the printed line to the prompt, it executes without an error.
Is there a way to read an if-statement from a file/array and then execute it in a script?
wget
command from the array, then print it, then execute it. I can also read and print theif
statement, and I'm trying to execute it. – alle_meije Mar 04 '23 at 13:02bash -x some_file
? – Chris Davies Mar 04 '23 at 13:12<<<
: firstc="if [[ a != b ]]; then echo false; fi"
and thenbash -x <<< $c
! Thank you very much! – alle_meije Mar 04 '23 at 14:58