I need to parse
all commands in bash
script and store them in list
variables. After parsing completed, then execute each list variables one by one.
But I found the following error.
Here is the test script for explaining this problem:
#!/bin/sh
mkdir -p /tmp/test
echo "hello" > /tmp/test/t.txt
run_directly() {
cd /tmp/test; echo "$(cat t.txt)"
}
run_in_time() {
# set cd and run
local -a cd_list=()
cd_list[0]="cd"
cd_list[1]="/tmp/test"
"${cd_list[@]}"
# set echo and run
local -a echo_list=()
echo_list[0]="echo"
echo_list[1]="$(cat t.txt)"
"${echo_list[@]}"
}
parse_before_run() {
# parse all commands from elsewhere
local -a cd_list=()
cd_list[0]="cd"
cd_list[1]="/tmp/test"
local -a echo_list=()
echo_list[0]="echo"
echo_list[1]="$(cat t.txt)"
# run cd
"${cd_list[@]}"
# run echo
"${echo_list[@]}"
}
echo "---------------run_directly-----------"
cd /tmp
run_directly
echo "---------------run_in_time-----------"
cd /tmp
run_in_time
echo "---------------parse_before_run-----------"
cd /tmp
parse_before_run
Here is the output:
---------------run_directly-----------
hello
---------------run_in_time-----------
hello
---------------parse_before_run-----------
cat: t.txt: No such file or directory
Here is the expected output:
---------------parse_before_run-----------
hello
The difference between “run_in_time” and “parse_before_run” is: The run_in_time
run the echo
after cd to that directory
while parse_before_run
parse that command before that directory is being created
.
How to write the echo_list[1]="$(cat t.txt)"
in parse_before_run
?
1