0

Running bash test.sh works. But running ./test.sh doesn't work. Why is this?

$PATH

Adams-MacBook-Pro:~ adamzerner$ echo $PATH
/Users/adamzerner/.rvm/gems/ruby-2.3.0/bin:/Users/adamzerner/.rvm/gems/ruby-2.3.0@global/bin:/Users/adamzerner/.rvm/rubies/ruby-2.3.0/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/adamzerner/.rvm/bin

test.sh

#!/bin/bash
echo Test

Console output:

Adams-MacBook-Pro:~ adamzerner$ ls
Applications    Downloads   Movies      Public
Desktop     Dropbox     Music       code
Documents   Library     Pictures    test.sh
Adams-MacBook-Pro:~ adamzerner$ ./test.sh
-bash: ./test.sh: Permission denied
Adams-MacBook-Pro:~ adamzerner$ sudo !!
sudo ./test.sh
Password:
sudo: ./test.sh: command not found
Adams-MacBook-Pro:~ adamzerner$ bash test.sh
Test
Adams-MacBook-Pro:~ adamzerner$

File permissions:

Adams-MacBook-Pro:~ adamzerner$ stat test.sh
16777220 1752325 -rw-r--r-- 1 adamzerner staff 0 22 "May 20 20:23:07 2016" "May 20 20:04:40 2016" "May 20 20:04:40 2016" "May 20 20:03:40 2016" 4096 8 0 test.sh
Adam Zerner
  • 17,797
  • 15
  • 90
  • 156
  • Does `test.sh` have execute permissions? Edit your post to include the output of `stat test.sh` – muru May 21 '16 at 03:26
  • @muru I don't know. a) How can I figure that out? b) Why would that lead to `bash` working but `./` not working? c) Wouldn't `sudo` fix that problem? – Adam Zerner May 21 '16 at 03:27
  • 1
    a) `stat test.sh` look for something like `rwxr-xr-x`, in particular, the `x`. b) `bash` has execute permissions, and you're running `bash` there, not the script directly, c) no. – muru May 21 '16 at 03:28
  • Also see: http://unix.stackexchange.com/questions/203371/run-script-sh-vs-bash-script-sh-permission-denied – muru May 21 '16 at 03:29

1 Answers1

4

Give the script execute permission:

chmod +x test.sh

Executing a file as a program requires execute permission. When you use bash test.sh, it's not being executed as a program, it's just an input file to the bash program, and that program just needs to be able to read it (just like cat test.sh only needs to be able to read it).

Barmar
  • 741,623
  • 53
  • 500
  • 612