Issues with special character '<' in Bash string?

試著忘記壹切 提交于 2020-01-25 08:48:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!