处理文本文件中的 bash 脚本和注释日志



我正在尝试读取一个很少注释以"#"开头的文本文件,我的 bash 脚本应该读取不以"#"开头的文本文件的行。 此外,我试图在两个日志中捕获 echo 语句的输出,并向其显示控制台窗口以供用户理解。

我尝试使用以下查询来捕获日志并在控制台中打印

执行 2>&1 1>>$logfile

为了读取文件的每一行并调用函数,我声明了一个数组并消除以"#"开头的行,我使用了以下查询。

declare -a cmd_array 
while read -r -a cmd_array | grep -vE '^(s*$|#)' 
do
"${cmd_array[@]}" 
done < "$text_file"

注意:我需要消除以"#"开头的行和要读取的其余行并按照声明放置在数组中。

Bash script 
***********
#! /bin/bash
Function_1()
{
now=$( date '+%Y%m%d%H%M' )
eval logfile="$1"_"$now".log
exec 2>&1 1>>$logfile     ### Capture echo output in log and printing in console 
#exec 3>&1 1>>$logfile 2>&1
echo " "
echo "############################"
echo "Function execution Begins"
echo "############################"
echo "Log file got created with file name as $1.log"
eval number=$1
eval  path=$2
echo "number= $number"
ls -lR $path >> temp.txt
if [ $? -eq 0 ]; then
echo " Above query executed."
else
echo "Query execution failed"
fi
echo "############################"
echo "Function execution Ends"
echo "############################"
echo " "
}
text_file=$1
echo $text_file
declare -a cmd_array  ### declaring a array 
while read -r -a cmd_array | grep -vE '^(s*$|#)'  ### Read each line in the file with doesnt starts with '#' & keep it in array
do
"${cmd_array[@]}" 
done < "$text_file"

Text file 
*********
####################################    
#Test
#Line2
####################################
Function_1 '125' '' ''
Function_1 '123' '' ''

考虑将 grep 输出管道到读取中:

declare -a cmd_array  ### declaring a array 
### Read each line in the file with doesnt starts with '#' & keep it in array
grep -vE '^(s*$|#)' < "$text_file" | while read -r -a cmd_array
do
"${cmd_array[@]}" 
done

我不清楚输出/日志记录注释。如果您需要将输出附加到文件中,除了 stdout/console(,请考虑使用"tee"(可能是"tee -a"(

我用输入文件进行了测试inputfile

echo a
Function_1 '125' '' ''
# skip me
Function_1 '123' '' ''
echo b

并编写了这个脚本:

declare -a cmd_array  ### declaring a array
while read -r -a cmd_array
do
echo "${cmd_array[@]}"
"${cmd_array[@]}"
echo
done < <(grep -vE '^(s*$|#)' inputfile)

有关在日志和控制台中显示输出的信息,请参阅 https://unix.stackexchange.com/a/145654/57293

正如@GordonDavisson评论中建议的那样,您将获得一个模拟结果

source inputfile

忽略注释和空行,并调用函数,所以我不确定你为什么要一个数组。 此命令可以包含在主脚本中,无需修改输入文件。

获取输入的另一个优点是处理字符串中的多行输入和#

Function_1 '123' 'this is the second parameter, the third will be on the next line' 
'third parameter for the Function_1 call'
echo "This echo continues
on the next line."
echo "Don't delete # comments in a string"
Function_1 '124' 'Parameter with #, interesting!' ''

最新更新