Shell Script Source: Not Found

2019-05-09 02:53发布

I am running the following simple script to test the block of code:

#!/bin/bash                                                                                                                         

# Load nvm and install latest production node                                                                                       
source $HOME/.nvm/nvm.sh
nvm install v0.10.12
nvm use v0.10.12

If the file name is test.sh with the above code, I get the following error:

test.sh: 5: test.sh: source: not found
test.sh: 6: test.sh: nvm: not found
test.sh: 7: test.sh: nvm: not found

Based on my review in SO, it appears the error with the script is originating at ==> source: not found. When I type this at CLI myself the code works fine. For some reason I am not able to execute this code through a shell script.

Any advice would be appreciated.

标签: bash shell
2条回答
在下西门庆
2楼-- · 2019-05-09 03:22

chmod +x $HOME/.nvm/nvm.sh

then

sh $HOME/.nvm/nvm.sh or . $HOME/.nvm/nvm.sh

查看更多
对你真心纯属浪费
3楼-- · 2019-05-09 03:25

Your shebang line says Bash but the symptom suggests that you are running it with sh, which doesn't have a source command. Superficially, changing source to just a dot will fix that, but of course, if the sourced file contains any Bashisms, it will fail on those instead (perhaps more subtly, with incorrect results but no error message).

#!/bin/sh                                      
# Load nvm and install latest production node
. $HOME/.nvm/nvm.sh
nvm install v0.10.12
nvm use v0.10.12

Usually, it is better to mark the script as executable and have the OS select the correct interpreter through the shebang mechanism; then you don't have to remember whether the script file contains Bash commands or sh commands or Python code or compiled code or whatever, nor notice if this changes from one version to another.

So instead of

sh script

you'd do

chmod +x ./script # the first time
./script

Once the permissions are correct, only the second line is needed. There are some minor additional caveats, which is why some busy developers sometimes give the simplest possible instructions for the immediate problem.

查看更多
登录 后发表回答