在heredoc中的源bash脚本中逐行读取文件

问题描述 投票:3回答:1

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

设置如下所示:

测试文件 - 〜/ file.txt

one==1.0.0
two==2.0.0
three==3.0.0
four==4.0.0

脚本A - 〜/ script_a.sh

#!/bin/bash
source script_b.sh
func_one

脚本B - 〜/ script_b.sh

#!/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
}

跑步

cd ~
bash script_a.sh

问题:为什么echo "$line"线没有产生任何输出?

bash
1个回答
3
投票

问题是bash在传递给su之前用$line替换它的值(没有)。逃离美元符号应该解决它。所以$line应该在script_b.sh的两个地方改为\$line

© www.soinside.com 2019 - 2024. All rights reserved.