我做了一个复杂而长的命令来成功登录一个站点。如果我在控制台中执行它,它就可以工作。但是,如果我在 bash 脚本中复制并粘贴同一行,它就不起作用。
我尝试了很多东西,但偶然发现如果我不使用这条线
#!/bin/sh
这行得通!为什么这发生在我的 mac OSX Lion 中?这个配置行在 bash 脚本中做了什么?
A bash script that is run via /bin/sh
runs in sh compatibility mode, which means that many bash-specific features (herestrings, process substitution, etc.) will not work.
sh-4.2$ cat < <(echo 123)
sh: syntax error near unexpected token `<'
If you want to be able to use full bash syntax, use #!/bin/bash
as your shebang line.
"#!/bin/sh" is a common idiom to insure that the correct interpreter is used to run the script. Here, "sh" is the "Bourne Shell". A good, standard "least common denominator" for shell scripts.
In your case, however, "#!/bin/sh" seems to be the wrong interpreter.
Here's a bit more info:
http://www.unix.com/answers-frequently-asked-questions/7077-what-does-usr-bin-ksh-mean.html
Originally, we only had one shell on unix. When you asked to run a command, the shell would attempt to invoke one of the exec() system calls on it. It the command was an executable, the exec would succeed and the command would run. If the exec() failed, the shell would not give up, instead it would try to interpet the command file as if it were a shell script.
Then unix got more shells and the situation became confused. Most folks would write scripts in one shell and type commands in another. And each shell had differing rules for feeding scripts to an interpreter.
This is when the "#! /" trick was invented. The idea was to let the kernel's exec() system calls succeed with shell scripts. When the kernel tries to exec() a file, it looks at the first 4 bytes which represent an integer called a magic number. This tells the kernel if it should try to run the file or not. So "#! /" was added to magic numbers that the kernel knows and it was extended to actually be able to run shell scripts by itself. But some people could not type "#! /", they kept leaving the space out. So the kernel was exended a bit again to allow "#!/" to work as a special 3 byte magic number.
So
#! /usr/bin/ksh
and#!/usr/bin/ksh
now mean the same thing. I always use the former since at least some kernels might still exist that don't understand the latter.And note that the first line is a signal to the kernel, and not to the shell. What happens now is that when shells try to run scripts via exec() they just succeed. And we never stumble on their various fallback schemes.
脚本的第一行可用于选择要使用的脚本解释器。
和
#!/bin/bash
你告诉 shell 调用 /bin/bash 解释器来执行你的脚本。确保#!/bin/bash 之前没有空格或空行,否则它将不起作用。