特殊字符“<"的问题在Bash字符串中? [英] Issues with special character '<' in Bash string?
问题描述
我正在制作一个接受可选标准输入的shell脚本.我有下面的代码片段. $ {file}只是写在包含所有文件名列表的txt文件中的fileName.在这种情况下,$ 2将是另一个程序(也是一个shell脚本).
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
并删除了<"来自stdIn变量.但是我不想这样做,因为我将不得不对其余代码进行重大更改.有人知道我当前的代码是什么以及如何解决该问题吗?非常感谢.
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.
推荐答案
您不能将<
运算符存储在变量中.相反,正确的做法是无条件地将输入从stdIn
中存储的文件名重定向,并将其初始化为/dev/stdin
,以便在没有其他输入文件合适的情况下,只需从标准输入中读取内容即可.
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
这篇关于特殊字符“<"的问题在Bash字符串中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!