Bash Scripting
Bash scripting allows you to automate tasks by writing sequences of commands in a file (a script) and then executing that file. This is incredibly powerful for repetitive tasks, system administration, and creating custom tools.
Creating and Running a Bash Script
-
Create a new file: Use a text editor (like
nano
orvim
) to create a new file. It’s common to use the.sh
extension for shell scripts, but it’s not strictly required.nano my_script.sh
-
Add the “shebang” line: At the very top of the file, add the following line:
#!/bin/bash
This line (called the “shebang”) tells the operating system which interpreter to use to execute the script (in this case,
bash
). -
Write your script: Add the commands you want to execute, one per line.
#!/bin/bash echo "Hello, world!" echo "The current date is: $(date)"
-
Save the file: In
nano
, press Ctrl+O, then Enter, then Ctrl+X. -
Make the script executable: Use the
chmod
command to give the script execute permissions:chmod +x my_script.sh
-
Run the script: Execute the script using
./
:./my_script.sh
Sample Output:
Hello, world! The current date is: Tue Oct 29 10:30:00 UTC 2024
Variables
Variables store data (text or numbers) that you can use in your script.
-
Assigning Values:
my_variable="Hello" number=123
Note: There must be no spaces around the
=
sign. -
Accessing Values: Use a
$
before the variable name:echo $my_variable echo "The number is: $number"
-
User Input: Use the
read
command:#!/bin/bash echo "Enter your name:" read user_name echo "Hello, $user_name!"
Comments
Comments are lines that are ignored by the interpreter. They are used to explain your code.
# This is a single-line comment
# This is another comment.
# This script displays a greeting.
echo "Hello" # This comment is at the end of a line