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

时间:2018-01-01 03:58:28

标签: bash

我有两个脚本。脚本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"行没有产生任何输出?

1 个答案:

答案 0 :(得分:3)

问题是bash在传递给su之前用$line代替其值(无)。逃离美元符号应该解决它。因此,$line应在script_b.sh中的两个位置更改为\$line