如何在文件夹中搜索没有特定扩展名的 bash 脚本文件?
How do I search for bash script files without having a specific extension within a folder?
我想在 Array 的文件夹下找到 bash 个脚本文件。
但是 bash 脚本文件没有指定的扩展名。
我写了这样的东西:
for i in "${array[@]}"
do
# Here I will write the condition that the file is found in the folder $k
done
如果您的脚本的第一行有 #!/bin/bash
或 #!/bin/sh
(它们应该如此),那么您可以使用 file
命令来检查文件是否为脚本或没有。
例如,拿这个脚本:
#!/bin/bash
echo "I am a script!"
file filename.sh
的输出将是 filename.sh: Bourne-Again shell script, ASCII text executable
,这表明它是一个 shell 脚本。注意file
命令不使用文件的扩展名来表示其格式,而是使用文件的内容。
如果你的文件开头没有这些行,你可以尝试 运行 每个文件(命令:bash filename.ext
)并检查它是否是 运行 通过检查变量 ${?}
的值来判断是否成功。这不是一个干净的方法,但如果您没有其他选择,它肯定会有所帮助。
文件命令确定文件类型。
例如
#!/bin/bash
arr=(~/*)
for i in "${arr[@]}"
do
type=`file -b $i | awk '{print }'`
if [[ $type = shell ]];then
echo $i is a shell script
fi
done
我想在 Array 的文件夹下找到 bash 个脚本文件。 但是 bash 脚本文件没有指定的扩展名。 我写了这样的东西:
for i in "${array[@]}"
do
# Here I will write the condition that the file is found in the folder $k
done
如果您的脚本的第一行有 #!/bin/bash
或 #!/bin/sh
(它们应该如此),那么您可以使用 file
命令来检查文件是否为脚本或没有。
例如,拿这个脚本:
#!/bin/bash
echo "I am a script!"
file filename.sh
的输出将是 filename.sh: Bourne-Again shell script, ASCII text executable
,这表明它是一个 shell 脚本。注意file
命令不使用文件的扩展名来表示其格式,而是使用文件的内容。
如果你的文件开头没有这些行,你可以尝试 运行 每个文件(命令:bash filename.ext
)并检查它是否是 运行 通过检查变量 ${?}
的值来判断是否成功。这不是一个干净的方法,但如果您没有其他选择,它肯定会有所帮助。
文件命令确定文件类型。 例如
#!/bin/bash
arr=(~/*)
for i in "${arr[@]}"
do
type=`file -b $i | awk '{print }'`
if [[ $type = shell ]];then
echo $i is a shell script
fi
done