I have an assignment wherein I am required to use the file command to check if a file is an executable type or not.
The wording used in the assignment is as follows:
The file command should be used to determine generically what kind of file the argument is and in particular if the file is an executable type or not. The output of the file command will include the special "executable" keyword if the file is an executable type.
Further on in the question, it states:
- Use file and look for the "executable" keyword in the output to determine if the file is an executable type or not.
I have so far been unable to find any documentation that explains how to do this. When I test this on a bash script in CentOS8, it returns this as output:
validate.sh: ASCII text
Edit1/found_the_answer_edit: I tried using ti7’s idea of using a test script and it got the same output as what they had gotten. Which got me thinking. The scripts for my assignments are required to have some formatting done to them. Specifically, in order to get credit for our scripts, we must have:
#START SCRIPT
#username
``
at the beginning of the file and:
#END SCRIPT
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"
2
Answers
Your script
validate.sh
probably isn’t executable asfile
determines it! This is probably because the header is wrong on itOnce that’s settled, you can check for the
executable
keyword in the response, perhaps withgrep
If you’re not forced to use
file
, using test’s-x
arg may be much better as suggested here, asfile
doesn’t check permissions, rather that the file format is executableNote the test command command is actually
[
or[[
with subtle differencesYou can check the permissions on it with
ls
, which lists files in a directory and optionally properties of themYou can make your script executable with
chmod
(trivially,chmod +x
)Not sure if this is actually bash running on Windows and so maybe WSL. If it is, file will actually return that a given Windows exe file is executable.
i.e.
With this in mind, you can pipe through to grep and test the output i.e.