Problem executing bash file

2019-03-03 07:18发布

HI there!

I've run into some problem while learning to combine .sh files and PHP. I've create a file test.sh and in that file I call a PHP file called test.php.

If I double click on the .sh file then it runs perfectly but when I try to run it from the terminal I get "command not found". I'm in the exact folder as my .sh file but it wont work. Here's my test.sh:

#!/bin/bash
LIB=${0/%cli/}
exec php -q ${LIB}test.php one two three
exit; 

When I doubleclick on the test.sh file then it returns the argv array like it suppost to. But why can't I run it from terminal?

标签: php bash shell
5条回答
霸刀☆藐视天下
2楼-- · 2019-03-03 07:50

Is execute bit enabled?

chmod +x test.sh
查看更多
3楼-- · 2019-03-03 07:52

Your $PATH variable may not include '.' - so the shell may not be able to find the command to run.

As others have said, sh ./file.sh will work...

查看更多
做个烂人
4楼-- · 2019-03-03 07:52

Another option is to run it with sh (or bash, if sh on your machine isn't bash and the script uses bashims)

sh filename.sh
bash filename.sh

This will work whether or not the file is executable or in $PATH

查看更多
Anthone
5楼-- · 2019-03-03 08:08

It is possible that your environment is different when launching from the Terminal and when launching via a double-click. Try executing which php and echo $PATH from the Terminal to see what the deal is.

EDIT 1
As others have noted, if your "command not found" is referring to the shell script and not php, then you probably forgot to include the "./" before the name of the script (i.e. ./test.sh). Also, don't forget to make it executable by invoking chmod a+x test.sh. The reason for this is that PATH does not include the current directory (i.e. "."), because doing so would be a security risk (e.g. folders with a ton of files in them including a fake "ssh" which could then intercept your password or the like).

EDIT 2
Also, I don't know about you, but ${0/%cli/} is evaluating to -bash from within my Terminal. Are you sure that's what you wanted it to expand to? Perhaps you should specify the exact filename.

查看更多
该账号已被封号
6楼-- · 2019-03-03 08:12

use ./filename.sh

no matter if your are in the same folder or not, without giving ./ the system is searching the path variable. (/bin/, /usr/bin and so on)

查看更多
登录 后发表回答