问题
I am making a shell script that takes an optional standard input. I have a snippet of the code below. ${file} is just a fileName that is written in a txt file containing a list of all file names. $2 in this case would be another program (a shell script too).
if [ -f ${file}.in ]; then #if ${file}.in exists in current directory
stdIn="< ${file}.in" #set optional stdIn
fi
if ! [ -f ${file}.args ]; then #if ${file}.args does not exist in curr directory
$2 $stdIn > ${file}.out #run the $2 program with the optional standard input and redirect the output to a .out file
For some reason, the '<' character isn't interpreted correctly. This works fine if I changed the line to
$2 < $stdIn > ${file}.out
and removed the '<' from the stdIn variable. But I don't want to do that because I will have to make major changes to the rest of my code. Anybody know what and how to fix the issue with my current code? Thanks a lot.
回答1:
You cannot store the <
operator in a variable. Instead, the correct thing to do is unconditionally redirect input from the file name stored in stdIn
, and initialize it to /dev/stdin
so that you simply read from standard input if no other input file is appropriate.
stdIn=/dev/stdin
if [ -f "${file}.in" ]; then
stdIn="${file}.in" #set optional stdIn
fi
if ! [ -f "${file}.args" ]; then
"$2" < "$stdIn" > "${file}.out"
fi
来源:https://stackoverflow.com/questions/46369289/issues-with-special-character-in-bash-string