Your First Script: #!/bin/bash and chmod +x

A script is just commands in a file

Everything you type at the prompt can go into a file and run as one. Such a file is a script. Here's the smallest useful one:

cat greet.sh

In the terminal

student@vulntech:~$ cat greet.sh
echo "Hello from a script"
echo "Today is $(date +%A)"

The first line is special. #! (the shebang) followed by a path tells Linux which program should run the file. #!/bin/bash means run this with bash. Every other line starting with # is a comment: a note for people, ignored when the script runs.

Make it executable, then run it

A fresh script is just a text file. Try to run it and you're refused, because it doesn't have execute permission. Add it with chmod +x (from the permissions module), then run it with ./ in front, which means the file here in this folder:

./greet.sh
chmod +x greet.sh
./greet.sh

In the terminal

student@vulntech:~$ ./greet.sh
-bash: ./greet.sh: Permission denied
student@vulntech:~$ chmod +x greet.sh
student@vulntech:~$ ./greet.sh
Hello from a script
Today is Saturday

Think of it like this: The shebang is a note clipped to the front of a document saying which app to open it with. Double-click (./greet.sh) and the right program starts automatically.

Writing the file

Use nano greet.sh to write a script by hand. In these lessons the files are already written for you; when you build your own, start it like this:

cat <<'EOF' > hello.sh
#!/bin/bash
# My first script
echo "Hi, I am $USER"
EOF
chmod +x hello.sh
./hello.sh

In the terminal

student@vulntech:~$ cat <<'EOF' > hello.sh
> #!/bin/bash
> # My first script
> echo "Hi, I am $USER"
> EOF
student@vulntech:~$ chmod +x hello.sh
student@vulntech:~$ ./hello.sh
Hi, I am student

Common mistake: Permission denied means you forgot chmod +x. not found for a script in the current folder means you forgot the ./ in front: the shell only searches the folders in $PATH, and . isn't one of them.

Tip: You can also run a script without chmod +x by handing it to bash yourself: bash greet.sh. Handy for a quick test.

Remember: A script starts with #!/bin/bash. # ... is a comment. Make it runnable with chmod +x, then run it with ./name.sh.

HOME LEARN COMMUNITY DASHBOARD
Practice terminal Starting…