运行shell脚本为./script.sh和sh script.sh之间的区别是什么

Rit*_*yak 18 unix shell scripting

我有一个看起来像这样的脚本

#!/bin/bash

function something() {
 echo "hello world!!"
}

something | tee logfile 
Run Code Online (Sandbox Code Playgroud)

我已经为这个文件设置了执行权限,当我尝试像这样运行文件时

 $./script.sh
Run Code Online (Sandbox Code Playgroud)

它运行得很好,但是当我在命令行上运行它时,就像这样

$sh script.sh 
Run Code Online (Sandbox Code Playgroud)

它引发了一个错误.为什么会发生这种情况,以及解决这个问题的方法是什么.

Chr*_*ris 23

运行它./script.sh将使内核读取第一行(shebang),然后调用bash来解释脚本.运行它sh script.sh使用你的系统默认的任何shell sh(在Ubuntu上这是Dash,它是sh兼容的,但不支持Bash的一些额外功能).

您可以通过调用它来修复它bash script.sh,或者如果它是您的机器,您可以更改/bin/sh为bash而不是当前的任何内容(通常只是通过符号链接 - rm /bin/sh && ln -s /bin/bash /bin/sh).或者你可以使用,./script.sh如果它已经工作;)

如果您的shell确实是破折号,并且您希望修改脚本以兼容,则https://wiki.ubuntu.com/DashAsBinSh提供了有用的差异指南.在您的示例中,您似乎只需要删除function关键字.