Adam Zerner Adam Zerner - 6 months ago 16
Linux Question

Why does bash test.sh work but not ./test.sh?

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

Answer

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).