What does chmod +x actually do?
Why your Bash script says "Permission denied", and the one-line fix.
You wrote your first Bash script, typed ./hello.sh, and got this:
bash: ./hello.sh: Permission denied
Nothing is broken. Linux and macOS just don’t let a file run as a program unless you say so.
Permissions in one minute
Every file has three permissions: read (r), write (w) and execute (x). A new text file can be read and written, but not executed. You can see them with ls -l:
-rw-r--r-- 1 sam staff 42 Nov 20 10:00 hello.sh
No x anywhere, so it can’t run.
The fix
chmod +x hello.sh
chmod means change mode, and +x means “add execute permission”. Check again:
-rwxr-xr-x 1 sam staff 42 Nov 20 10:00 hello.sh
Now ./hello.sh works.
Don’t forget the first line
For ./hello.sh to work, the script should start with a shebang line that says which program runs it:
#!/usr/bin/env bash
echo "Hello from Bash!"
In plain English
#!/usr/bin/env bash means “run this file with Bash”. chmod +x means “this file is allowed to run”. You need both.
You can always skip both and run bash hello.sh instead. That works without the execute permission.
Try it yourself
Create hello.sh with the two lines above, try ./hello.sh, see the error, fix it with chmod +x, and run it again.