簡體   English   中英

如何使用 Bash 中的 file 命令檢查文件是否可執行?

[英]How do I check if a file is executable using the file command in Bash?

我有一項作業,其中要求我使用 file 命令來檢查文件是否為可執行類型。

作業中使用的措辭如下:

file 命令應該用於一般地確定參數是什么類型的文件,特別是文件是否是可執行類型。 如果文件是可執行類型,文件命令的輸出將包含特殊的“可執行”關鍵字。

進一步在問題中,它指出:

  1. 使用 file 並在輸出中查找“executable”關鍵字以確定文件是否為可執行類型。

到目前為止,我一直無法找到任何解釋如何執行此操作的文檔。 當我在 CentOS8 中的 bash 腳本上對此進行測試時,它會將其作為輸出返回:

validate.sh: ASCII text

Edit1/found_the_answer_edit:我嘗試使用 ti7 的使用測試腳本的想法,它得到的輸出與他們得到的輸出相同。 這讓我思考。 我的作業腳本需要對它們進行一些格式化。 具體來說,為了獲得我們腳本的榮譽,我們必須:

#START SCRIPT
#username
``
at the beginning of the file and:

#結束腳本

at the end of it. I deleted these bits in my validate.sh file and when I tested it again with the file command I got the same output that I got from the test script. So the answer is that there isn't anything special. File just can't deal with a file that doesn't start with "#!/bin/bash"

您的腳本validate.sh可能無法執行,因為file決定了它! 這可能是因為標題錯誤就可以了

% cat test.sh
#!/bin/bash
echo "foo"
% file test.sh
test.sh: Bourne-Again shell script text executable, ASCII text

一旦確定,您可以檢查響應中的executable關鍵字,也許使用grep

% file test.sh | grep -q executable ; echo $?
0
% touch test-empty.sh
% file test-empty.sh | grep -q executable ; echo $?
1

如果您不是被迫使用file ,則按照此處的建議使用 test 的-x arg 可能會好得多,因為file不檢查權限,而是文件格式是可執行的

注意 test 命令命令實際上是[[[有細微的差別

[[ -x "validate.sh" ]] && echo "executable" || echo "not executable"

您可以使用ls來檢查它的權限,它會列出目錄中的文件以及它們的可選屬性

ls -lhaF

您可以使用chmod使您的腳本可執行(簡單地說, chmod +x

不確定這是否真的是在 Windows 上運行的 bash,所以可能是 WSL。 如果是,文件實際上將返回給定的 Windows exe 文件是可執行的。

IE

file write.exe

write.exe: PE32+ executable (GUI) x86-64, for MS Windows

考慮到這一點,您可以通過管道傳遞到 grep 並測試輸出,即

file write.exe | grep -q executable && echo "Executable" || echo "Not executable"

Executable

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM