Bash script always prints “Command Not Found”

2019-01-01 10:41发布

Every time I run a script using bash scriptname.sh from the command line in Debian, I get Command Not found and then the result of the script. So the script works but there is always a Command Not Found statement printed on screen.

I am running the script from the /var folder.

Here is the script:

#!/bin/bash

echo Hello World

I run it by typing the following:

bash testscript.sh

UPDATE - the problem appears to the blank lines. Each blank line is resulting in a command not found. Why would this occur?

16条回答
看淡一切
2楼-- · 2019-01-01 11:13

If the script does its job (relatively) well, then it's running okay. Your problem is probably a single line in the file referencing a program that's either not on the path, not installed, misspelled, or something similar.

One way is to place a set -x at the top of your script or run it with bash -x instead of just bash - this will output the lines before executing them and you usually just need to look at the command output immediately before the error to see what's causing the problem

If, as you say, it's the blank lines causing the problems, you might want to check what's actaully in them. Run:

od -xcb testscript.sh

and make sure there's no "invisible" funny characters like the CTRL-M (carriage return) you may get by using a Windows-type editor.

查看更多
后来的你喜欢了谁
3楼-- · 2019-01-01 11:14

I was also having some of the Cannot execute command. Everything looked correct, but in fact I was having a non-breakable space   right before my command which was ofcourse impossible to spot with the naked eye:

if [[ "true" ]]; then
   highlight --syntax js "var i = 0;"
fi

Which, in Vim, looked like:

if [[ "true" ]]; then
  highlight --syntax js "var i = 0;"
fi

Only after running the Bash script checker shellcheck did I find the problem.

查看更多
余生无你
4楼-- · 2019-01-01 11:19

If you have Notepad++ and you get this .sh Error Message: "command not found" or this autoconf Error Message "line 615: ../../autoconf/bin/autom4te: No such file or directory".

On your Notepad++, Go to Edit -> EOL Conversion then check Macinthos(CR). This will edit your files. I also encourage to check all files with this command, because soon such an error will occur.

查看更多
时光乱了年华
5楼-- · 2019-01-01 11:19

This might be trivial and not related to the OP's question, but I often made this mistaken at the beginning when I was learning scripting

VAR_NAME = $(hostname)
echo "the hostname is ${VAR_NAME}"  

This will produce 'command not found' response. The correct way is to eliminate the spaces

VAR_NAME=$(hostname)
查看更多
不流泪的眼
6楼-- · 2019-01-01 11:19

Add the current directory ( . ) to PATH to be able to execute a script, just by typing in its name, that resides in the current directory:

PATH=.:$PATH
查看更多
浮光初槿花落
7楼-- · 2019-01-01 11:20

I ran into this today, absentmindedly copying the dollar command prompt $ (ahead of a command string) into the script.

查看更多
登录 后发表回答