I have a function that is supposed to evaluate the command passed to it as a string and display the output if the command failed. However, I'm getting some problems:
$(echo "pwd")
works well (I see the files and directories). But, when I want to retrieve the output of this command:
var=$(echo "pwd")
echo ${var}
I get the following output:
pwd
Why does assigning a variable to the output cause such a significant change? I've looked it up and it seems to be the recommended way of retrieving the output (i.e. see here).
Also, I based on this question and tried a different approach:
cmd="ls"
$cmd
file1 file2 dir1
a=$cmd
echo ${a}
ls
The result is the same like for the previous approach. I have the same issue with the answers here and here.
What am I doing wrong? How do I get the output of a string evaluated as a command?
Edit: I tried using $()
:
> var="pwd"
> ${var}
/c/Users/myDir
> $(${var})
bash: /c/Users/myDir: Is a directory
Edit2: I need to change the current working directory, so, as far as I know, I can't use $()
. How can I get the output without creating a subprocess?