Is there any way to convert a literal to a non literal variable in bash? [duplicate]
My goal is to have an array that includes specific commands for each value. However to even get bash to process the array I need to create literal values surrounded by ''
When trying to process through the array the literal values (that include variable syntax) are processed as their literal name instead of their variable name. Is there anyway to convert a literal value to a non literal value?
Here is an example of what I mean:
#!/bin/bash
dir=C
echo "Non literal"
ls $dir
echo "Literal"
'ls $dir'
echo "variable with literal
cmd='ls $dir'
echo $cmd
echo "$cmd"
$ ./test.sh
Non literal
01_hello_world Modern_C PLE_LinkedIn_Learning_C The_C_Programming_Language
Literal
./test.sh: line 6: ls $dir: command not found
variable with literal
ls $dir
ls $dir
From the "Literal statement" I want to be able to convert 'ls $dir'
to "ls $dir"
so $dir
gets processed as C
.
Is this possible?
EDIT
I want to include my actual script that will process a list of commands from an array (my original goal):
#!/bin/bash
dir=C
tree_cmd=tree
run_cmds(){
if [[ -z "$@" ]]; then
echo "Array is empty"
else
for i in "$@"; do
$i
done
fi
}
arr=(
'ls $dir'
'cat $dir/01_hello_world'
'$tree_cmd $dir'
)
run_cmds "${arr[@]}"
Do not store commands in strings. Use functions.
Quote variable expansion.
Use shellcheck to check your script.
#!/bin/bash
dir=C
tree_cmd=tree
run_cmds(){
if ((!$#)); then
echo "No argumetns given"
else
local i
for i in "$@"; do
"$i"
done
fi
}
cmd_1() {
ls "$dir"
}
cmd_2() {
cat "$dir"/01_hello_world
}
cmd_3() {
"$tree_cmd" "$dir"
}
arr=( cmd_1 cmd_2 cmd_3 )
run_cmds "${arr[@]}"
If you really want to store commands in strings, for example for short testing purposes, ignoring some best practices, see https://mywiki.wooledge.org/BashFAQ/048 . Still quote variable expansions. You can do:
#!/bin/bash
dir=C
tree_cmd=tree
run_cmds(){
local i
for i in "$@"; do
eval "$i"
done
}
arr=(
'ls "$dir"'
'cat "$dir"/01_hello_world'
'"$tree_cmd" "$dir"'
)
run_cmds "${arr[@]}"