如何在不输入 bash 的情况下执行自定义脚本?

0 bash scripts

我想运行我的自定义脚本,但每次需要执行它时,我都必须在脚本名称之前输入 bash。但我想像运行其他脚本一样运行它,ls git sed chmod例如不需要在脚本名称之前输入 bash 。

我在这里没有找到任何解决方案,但最接近的是这个Bash 脚本不执行任何操作

我创建了一个名为test

#!/bin/bash

echo Hello
Run Code Online (Sandbox Code Playgroud)

但是当我在终端上输入它时,它没有给出错误并且不打印任何内容

user@notebook:~$ test
user@notebook:~$
Run Code Online (Sandbox Code Playgroud)

但当我用 bash 键入它时它会起作用

user@notebook:~$ bash test
Hello
user@notebook:~$
Run Code Online (Sandbox Code Playgroud)

我已将文件添加到~/.local/bin/,授予它权限chmod a+x test并在我的变量~/.local/bin中设置。PATH


我的stat /bin/bash

  File: /bin/bash
  Size: 1396520     Blocks: 2728       IO Block: 4096   regular file
Device: 806h/2054d  Inode: 30408799    Links: 1
Access: (0755/-rwxr-xr-x)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2023-05-07 12:23:17.179593764 +0500
Modify: 2022-01-06 21:23:33.000000000 +0500
Change: 2022-10-08 20:47:19.225627603 +0500
Birth: 2022-10-08 20:47:19.217622335 +0500
Run Code Online (Sandbox Code Playgroud)

我的stat /bin

  File: /bin -> usr/bin
  Size: 7           Blocks: 0          IO Block: 4096   symbolic link
Device: 806h/2054d  Inode: 12          Links: 1
Access: (0777/lrwxrwxrwx)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2023-05-07 12:22:43.299594371 +0500
Modify: 2022-10-08 20:47:18.020812502 +0500
Change: 2022-10-08 20:47:18.020812502 +0500
Birth: 2022-10-08 20:47:18.020812502 +0500
Run Code Online (Sandbox Code Playgroud)

的输出type -a test是:

test is a shell builtin 
test is /home/saad/.local/bin/test 
test is /usr/bin/test 
test is /bin/test 
Run Code Online (Sandbox Code Playgroud)

Art*_*ild 5

这泄露了真正发生的事情:

的输出type -a test是:

test is a shell builtin 
test is /home/saad/.local/bin/test
test is /usr/bin/test
test is /bin/test
Run Code Online (Sandbox Code Playgroud)
  1. 您的脚本的名称与内置命令test相同

  2. 切勿将脚本命名为与内部命令完全相同的名称 - 这会产生不良后果。

  3. 因此,您只需将脚本文件命名为(或任何其他内部命令)以外的名称即可。test

  4. 如果您想运行自己的脚本而不是标准应用程序(例如ls),您应该使用脚本的名称和完整路径创建一个别名,例如:

    alias ls='/home/saad/.local/bin/myscript'
    
    Run Code Online (Sandbox Code Playgroud)
重要的提示:

下次您提出此类问题时,请提供正确的脚本名称,而不是占位符名称。现在您已经包含了正确的名称,对于这里的许多用户来说,很明显它被称为test,这与内部命令相同。