Shell Your First Script
A script is a text file that holds shell commands. The shell reads the file and runs its commands in order, as if you had typed them.
Write a script
A heredoc writes the script file in one go.
cat > hello.sh <<'EOF'
#!/bin/bash
echo "Hello from a script"
EOF
chmod +x hello.sh
./hello.shRead the script back
The file holds the shebang and the command.
cat hello.shCheck that it is runnable
Test -x is true when the file can run.
test -x hello.sh && echo "hello.sh is runnable"A script with two commands
Commands in a script run in order.
cat > greet.sh <<'EOF'
#!/bin/bash
echo "Good morning"
echo "Good afternoon"
EOF
chmod +x greet.sh
./greet.shExample
cat > show-notes.sh <<'EOF'
#!/bin/bash
echo "My notes:"
cat notes.txt
echo "Total lines:"
wc -l < notes.txt
EOF
chmod +x show-notes.sh
./show-notes.shKey points
- Script: a text file that holds commands for the shell to run.
- Shebang: #!/bin/bash is the first line, and it names the shell for the script.
- Executable: chmod +x makes a script runnable.
- Run a script: ./script.sh runs the script in the current folder.
In this example, the script prints a heading. Then it shows notes.txt with cat. Then it prints a second heading. Then it counts the lines with wc -l.
Note
./ is needed because the current folder is not searched for commands.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the first line #!/bin/bash do?