【发布时间】:2021-03-11 15:20:54
【问题描述】:
如何验证以 .sh 结尾的指定目录中的每个 .sh 文件,以确保第一行是 #!/bin/bash?
我希望每个文件的输出为 filename.sh is valid 或 filename.sh is missing the header。
【问题讨论】:
标签: linux bash shell sh linux-mint
如何验证以 .sh 结尾的指定目录中的每个 .sh 文件,以确保第一行是 #!/bin/bash?
我希望每个文件的输出为 filename.sh is valid 或 filename.sh is missing the header。
【问题讨论】:
标签: linux bash shell sh linux-mint
可能是这样的
awk 'FNR == 1 { if ($0 == "#!/bin/bash") {
print FILENAME, "is valid"
} else {
print FILENAME, "is missing the header"
}
nextfile
}' *.sh
【讨论】:
还可以考虑纯 bash 解决方案。它不调用任何其他进程。
请注意,有效文件可能在#! 和/bin/bash 之间包含空格。
#! /bin/bash
PAT="^#! */bin/bash"
for file in *.sh ; do
line=
read line < $file
if [[ "$line" =~ $PAT ]] ; then
echo "$file is valid"
else
echo "$file is missing the header"
fi
done
如果您需要支持其他解释器(例如 bin/sh),您可以扩展该模式以包含其他 shell
PAT="#! *(/bin/bash|/bin/sh)"
【讨论】: