Shell scripting is a powerful tool for automating tasks and executing commands in Linux. Here's a beginner-friendly guide to writing and executing your first shell script.
-
Choose a Text Editor: Open your preferred text editor. Common choices include
nano
,vim
, orgedit
. -
Create a New File: Start a new file by typing:
nano my_script.sh
Replace
my_script.sh
with your desired file name. -
Add SheBang: Begin your script with a SheBang line to specify the shell interpreter. For bash, use:
#!/bin/bash
-
Write Your Commands: Add the commands you want your script to execute. For example:
#!/bin/bash echo "Hello, world!"
-
Save and Exit: Press
Ctrl + X
to exit nano. Confirm to save changes by typingY
, then pressEnter
.
- Set Permissions: Make your script executable using the
chmod
command:chmod +x my_script.sh
-
Run Your Script: Execute your script using the
./
notation followed by the script name:./my_script.sh
-
View Output: Your script's output will be displayed in the terminal.
Here's an example of a simple shell script:
#!/bin/bash
echo "Hello, world!"