File redirection fails in Bash script, but not Bash terminal

Viewed 2332

I am having a problem where cmd1 works, but not cmd2 in my Bash script ending in .sh. I have made the Bash script executable.

Additionally, I can execute cmd2 just fine from my Bash terminal. I have tried to make a minimally reproducible example, but my larger goal is to run a complicated executable with command line arguments and pass output to a file that may or may not exist (rather than displaying the output in the terminal).

Replacing > with >> also gives the same error in the script, but not the terminal.

My Bash script:

#!/bin/bash 
cmd1="cat test.txt"   
cmd2="cat test.txt > a" 
echo $cmd1   
$cmd1  
echo $cmd2   
$cmd2

test.txt has the words "dog" and "cat" on two separate lines without quotes.

3 Answers
Related