Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在herdoc内的源代码bash脚本中逐行读取文件_Bash - Fatal编程技术网

在herdoc内的源代码bash脚本中逐行读取文件

在herdoc内的源代码bash脚本中逐行读取文件,bash,Bash,我有两个脚本。脚本A包括脚本B并调用脚本B中的函数 设置如下所示: 测试文件-~/file.txt one==1.0.0 two==2.0.0 three==3.0.0 four==4.0.0 脚本A-~/Script\u A.sh #!/bin/bash source script_b.sh func_one #!/bin/bash # Note: don't forget to change the spaces to tabs else heredoc won't work my_us

我有两个脚本。脚本A包括脚本B并调用脚本B中的函数

设置如下所示:

测试文件-~/file.txt

one==1.0.0
two==2.0.0
three==3.0.0
four==4.0.0
脚本A-~/Script\u A.sh

#!/bin/bash
source script_b.sh
func_one
#!/bin/bash
# Note: don't forget to change the spaces to tabs else heredoc won't work
my_user=$USER
func_two() {
    # Here, I need run everything in the heredoc as user $my_user
    sudo su - $my_user -s /bin/bash <<- EOF            
        while read -r line || [[ -n "$line" ]];
        do
            # **This is the problem line**
            # I can confirm that all the lines are being 
            #  read but echo displays nothing
            echo "$line"
            # The line below will be printed 4 times as there are 4 lines in the file of interest
            echo "Test"
        done < "/home/$my_user/file.txt"
    EOF
}

func_one() {
    func_two
}
脚本B-~/Script_B.sh

#!/bin/bash
source script_b.sh
func_one
#!/bin/bash
# Note: don't forget to change the spaces to tabs else heredoc won't work
my_user=$USER
func_two() {
    # Here, I need run everything in the heredoc as user $my_user
    sudo su - $my_user -s /bin/bash <<- EOF            
        while read -r line || [[ -n "$line" ]];
        do
            # **This is the problem line**
            # I can confirm that all the lines are being 
            #  read but echo displays nothing
            echo "$line"
            # The line below will be printed 4 times as there are 4 lines in the file of interest
            echo "Test"
        done < "/home/$my_user/file.txt"
    EOF
}

func_one() {
    func_two
}

问题:为什么行
回送“$line”
不产生任何输出?

问题是bash在传递给su之前用它的值替换了
$line
。摆脱美元符号应该可以解决这个问题。因此,脚本中的两个位置都应将
$line
更改为
\$line

如何确认所有行都已读取?如果在您担心的行上方添加行
回显测试
,您会得到任何输出吗?@iBug I
回显
沿我想要的行显示一个简单文本,并打印相同的次数由于文件中有行。@jwpfox For
echo“test”
test
的打印次数与感兴趣的文件中有行的打印次数相同。您能制作一个我们可以测试的文件吗?不需要“迷你康达”的东西,不管是什么?如果您不断地从脚本中删除复杂性,那么在什么情况下它的行为会像您期望的那样?