3

During one of my interviews I came across a very basic question about shell scripting and I could not find the answer for it. Question was: If first line of the script is "#!/bin/ksh" can I execute it on bash?

My answer was No. And the reason to include a directive as the first line of script is to tell which interpreter needs to be used. But the interviewer's answer to this question was Yes. Can anybody explain me the reason?

2
  • Maybe they meant "execute it using ./script.sh which would of course work regardless of which shell is used to invoke it. Commented Sep 7, 2013 at 23:39
  • 1
    Attempting ./script.sh would generate an error if /bin/ksh doesn't exist. But you can do sh script.sh or bash script.sh and it won't complain about /bin/ksh being missing. Commented Sep 8, 2013 at 0:02

1 Answer 1

4

Yeah, you can:

bash yourscript

Of course it will throw some errors if there are language specific features. But the question did not specify if it should work correctly or not.

From man bash:

the first argument is assumed to be the name of a file containing shell commands. If bash is invoked in this fashion, $0 is set to the name of the file, and the positional parameters are set to the remaining arguments. Bash reads and executes commands from this file, then exits. Bash's exit status is the exit status of the last command executed in the script. If no commands are executed, the exit status is 0. An attempt is first made to open the file in the current directory, and, if no file is found, then the shell searches the directories in PATH for the script

In fact, that's exactly what program loader is going to do. Here's a quote from wikipedia shebang article:

Under Unix-like operating systems, when a script with a shebang is run as a program, the program loader parses the rest of the script's initial line as an interpreter directive; the specified interpreter program is run instead, passing to it as an argument the path that was initially used when attempting to run the script. For example, if a script is named with the path "path/to/script", and it starts with the following line:

#!/bin/sh

then the program loader is instructed to run the program "/bin/sh" instead (usually this is the Bourne shell or a compatible shell), passing "path/to/script" as the first argument.

Edit:

If they say Oh, but can you execute it in bash just by using ./script ? then the answer is still yes. Remove /bin/ksh and copy(or link) bash to the same path. Taa-daa! Might require root privileges though.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.