简体   繁体   中英

.sh File not executing on Linux

Does anyone know why the executing a shell script as such ./hello.sh would not work but bash hello.sh does?

cat /tmp/hello.sh

#!/bin/bash
echo "Hello World"

When I run the script as such: bash /tmp/hello.sh I get Hello World

But when I run ./tmp/hello.sh I get bash: ./tmp/hello.sh: Permission denied

The file is executable, so I'm not sure what the issue is.

UPDATE:

ls -ld /tmp 
drwxrwxrwt. 13 root root 340 Jan 18 11:02 /tmp
ls -ld ./tmp
drwxrwxrwt. 13 root root 340 Jan 18 11:02 ./tmp

Try /tmp/hello.sh to run the script, instead of ./tmp/hello.sh .

The . in the latter command is not a keyword or reserved word. It is just a reference to your current working directory. If your current working directory is not / , then ./tmp/hello.sh is certainly not the same file as /tmp/hello.sh .


You may have made this mistake because the . is required if you are running an executable that is in your current working directory (provided that that current working directory is not in $PATH ). Hence bash my_script.sh or cat my_script.sh works, but ./my_script.sh (or indeed bash./my_script.sh ) does. The reason for this is that if the command line interpreter sees a command which can't be assumed to be a filepath, it will automatically look in $PATH to find it. This is unlike, for example, Windows, which automatically includes the current working directory as part of the list of paths where it searches for commands.

This is why you can run ls in any directory, even if said directory actually contains a file by the name of ls , and it will not automatically try to run that file as an executable; it will use the ls in $PATH instead. If, however, you specify as a command anything that is obviously a relative or absolute path, the shell will understand that you are explicitly specifying a path to an executable, and not try and look in $PATH . Hence why ../my_script_in_parent_dir.sh or /tmp/temp_script.sh will work to run the script at the specified directory.

Make the file executable.

chmod +x shellfile.sh

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM