Executing Shell Script from current directory with

2019-06-17 04:57发布

I have created a file called "testfile" and made it executable using chmod +x testfile. In order to execute the file "testfile" i need to run the command ./testfile.

I need to know is there any way i could run the program without using ./ and execute the file using testfile command?

Shown below is a simple code inside the file "testfile"

echo Todays date is : 
date

3条回答
叼着烟拽天下
2楼-- · 2019-06-17 05:49

You can execute it without ./ by using:

sh testfile

Or

sh /path/to/file/testfile

Edit
If you want to execute the program directly with a command, what you can do is to define an alias:

alias execute_testfile="sh /path/to/file/testfile"

And then, you will execute the program whenever you write

execute_testfile

or whatever name you define.

To make this alias persistent, do include the alias ... line in your ~/.profile or ~/.bash_profile files.

查看更多
小情绪 Triste *
3楼-- · 2019-06-17 06:02

You need to add . to your PATH variable like this:

> echo 'echo Hello, World!' > mycommand
> mycommand
-bash: mycommand: command not found
> ./mycommand
Hello, World!
> PATH=".:$PATH";
> mycommand
Hello, World!
>
查看更多
ら.Afraid
4楼-- · 2019-06-17 06:04

You can define PATH variable in .profile file which you can find under your home directory.

vi ~/.profile

Add to the end of your .profile

/path/to/dir/:$PATH

Which translates to "add /path/to/dir/ to whatever the PATH variable is set"

If you want to add a directory to the PATH for all users of the system you can:

vi /etc/environment - edit, save your changes
source /etc/environment
echo $PATH - should now return your new PATH

Works on Ubuntu server, I would guess on all Debian distributions, I am not sure if other distributions have /etc/environment or if PATH is specified somewhere else

Aliasing is still a better solution

vi ~/.bashrc

Add to the end of the file

alias <your_script> ='/path/to/your_script.sh'

Log out, log back in - you shouldnt have to type ./.sh anymore'

查看更多
登录 后发表回答