Bash scripts follow a simple and readable syntax that closely resembles the Linux command line. However, scripting allows you to organize commands into a file and add logic like loops, conditions, and functions.
A script typically starts with the shebang line to specify the shell, and uses common Bash syntax rules for variables, commands, and comments.
Bash Syntax Examples
1. Start your script with a shebang:
This tells the system to use the Bash shell to interpret the script.
2. Use the echo command to display a message:
3. Add comments using #:
4. Use semicolons to write multiple commands on one line:
Important Points
- Every Bash script starts with
#!/bin/bash. - Use
#to add comments and document your code. - Use semicolons or line breaks to separate commands.
Try It Out!
Try creating a file called syntax.sh, write a basic script that prints two lines and includes a comment.
1. Create the file:
touch syntax.sh
2. Open it for editing:
nano syntax.sh
3. Type your script inside. For example:
#!/bin/bash # This is a simple script echo "Line 1" echo "Line 2"
4. Save and exit nano:
- Press
Ctrl + O, thenEnterto save - Press
Ctrl + Xto exit
5. Run the script:
bash syntax.sh
TD Bash PlayCloud
Please click the “Play” button to launch the terminal and wait for it to load. If you’re unable to type, kindly click the refresh button located at the upper right corner.