I have a script that looks like this
#!/bin/bash
function something() {
echo "hello world!!"
}
something | tee logfile
I have set the execute permission on this file and when I try running the file like this
$./script.sh
it runs perfectly fine, but when I run it on the command line like this
$sh script.sh
It throws up an error. Why does this happen and what are the ways in which I can fix this.
The . sh file is nothing but the shell script to install given application or to perform other tasks under Linux and UNIX like operating systems. The easiest way to run . sh shell script in Linux or UNIX is to type the following commands.
Shell scripting is scripting in any shell, whereas Bash scripting is scripting specifically for Bash. sh is a shell command-line interpreter of Unix/Unix-like operating systems. sh provides some built-in commands. bash is a superset of sh.
Run Bash Script Using sh Although not that popular anymore, modern Unix-like systems include the interpreter under /bin/sh. The output shows the symbolic link for the sh interpreter. Commonly, Debian and Debian-based systems (such as Ubuntu) link sh to dash, whereas other systems link to bash.
Running it as ./script.sh
will make the kernel read the first line (the shebang), and then invoke bash to interpret the script. Running it as sh script.sh
uses whatever shell your system defaults sh
to (on Ubuntu this is Dash, which is sh-compatible, but doesn't support some of the extra features of Bash).
You can fix it by invoking it as bash script.sh
, or if it's your machine you can change /bin/sh
to be bash and not whatever it is currently (usually just by symlinking it - rm /bin/sh && ln -s /bin/bash /bin/sh
). Or you can just use ./script.sh
instead if that's already working ;)
If your shell is indeed dash and you want to modify the script to be compatible, https://wiki.ubuntu.com/DashAsBinSh has a helpful guide to the differences. In your sample it looks like you'd just have to remove the function keyword.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With