Bash Scripting FundamentalsLesson 3.1
How to write your first Bash script
shebang line, script permissions, script execution, bash vs sh, comments, exit codes, script structure
A Bash Script Is a File of Commands
A Bash script is a plain text file containing shell commands, executed in sequence. The only thing that makes it a script is the shebang line at the top and executable permission on the file.
The Shebang Line
The first line #!/bin/bash tells the OS which interpreter to use. Without it, the system may use a different shell (sh, dash) which lacks Bash features. Always include it.
#!/bin/bash
# This is a comment
# Script: hello.sh
# Purpose: basic example
echo "Starting script..."
echo "Current directory: $(pwd)"
echo "Script name: $0"
# Exit with success code
exit 0Making It Executable and Running It
# Create the script
nano hello.sh # or use any editor
# Make it executable
chmod +x hello.sh
# Run it
./hello.sh
# Or run without making executable (bash interprets it)
bash hello.shExit Codes
Every command returns an exit code. 0 means success. Any non-zero value means failure. After any command, $? holds its exit code. Your scripts should always return 0 on success and a non-zero code on failure โ CI/CD systems rely on this to detect broken builds.
ls /nonexistent 2>/dev/null
echo "Exit code: $?" # prints 2