🎓 A1Learner
🔍
0 of 47 lessons completed

Bash File Permissions

File permissions control who can read, write, or run a file. Bash lets you check permissions and change them with a few short commands.

A new file is not executable

The touch command creates an empty file. A plain file like this cannot run as a program yet.

touch notes.txt
if [ -x notes.txt ]; then
  echo "notes.txt is executable"
else
  echo "notes.txt is not executable"
fi

Make a file executable

The chmod +x command adds the executable permission. The -x test now takes the true branch.

touch report.txt
chmod +x report.txt
if [ -x report.txt ]; then
  echo "report.txt is executable"
else
  echo "report.txt is not executable"
fi

Run a script with ./

A script needs its shebang line from the first line. Once it is executable, ./ before its name runs it directly.

echo '#!/bin/bash' > tool.sh
echo 'echo "Tool is running"' >> tool.sh
chmod +x tool.sh
./tool.sh

Example

echo '#!/bin/bash' > greet.sh
echo 'echo "Hello from greet.sh"' >> greet.sh
echo "Before chmod:"
if [ -x greet.sh ]; then
  echo "greet.sh is executable"
else
  echo "greet.sh is not executable"
fi
chmod +x greet.sh
echo "After chmod +x:"
if [ -x greet.sh ]; then
  echo "greet.sh is executable"
else
  echo "greet.sh is not executable"
fi
./greet.sh
chmod -x greet.sh
echo "After chmod -x:"
if [ -x greet.sh ]; then
  echo "greet.sh is executable"
else
  echo "greet.sh is not executable"
fi

Key points

  • Every file has permissions that say who can read, write, or run it.
  • The ls -l command shows a permission string at the start of each line.
  • The chmod command changes the permissions of a file.
  • The chmod +x command makes a file executable.
  • The chmod -x command removes the executable permission again.
  • The test [ -x file ] succeeds when the file is executable.

In this example, the script greet.sh starts out not executable. The chmod +x command makes it executable, so ./greet.sh runs it. The chmod -x command then removes that permission again.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does chmod +x tool.sh do?