Shell scripting allows for the automation of tasks in Unix-like operating systems. Below are fundamental concepts and constructs commonly used in shell scripts.
The shebang (#!) at the beginning of a script specifies the interpreter to execute the script.
#!/bin/bashVariables in shell scripts are defined without a type. They can store strings, integers, or arrays. Assign values to variables without spaces around the = sign.
name="Alice"
age=30
numbers=(1 2 3 4 5)To access the value of a variable, prefix the variable name with a $.
echo $name
echo ${numbers[2]}Comments in shell scripts start with a # and continue to the end of the line.
# This is a comment
echo "This is not a comment"The if statement evaluates a condition and executes a block of code if the condition is true.
if [ condition ]; then
# code block
elif [ condition ]; then
# code block
else
# code block
fiThe for loop iterates over a list of items.
#!/bin/bash
for i in 1 2 3; do
echo "Number: $i"
doneThe while loop executes a block of code as long as a condition is true.
#!/bin/bash
count=1
while [ $count -le 3 ]; do
echo "Count: $count"
((count++))
doneFunctions allow you to group code for reuse.
#!/bin/bash
greet() {
echo "Hello, $1!"
}
greet "Alice"The read command reads input from the user and assigns it to a variable.
#!/bin/bash
echo "Enter your name:"
read name
echo "Hello, $name!"The > operator redirects output to a file, overwriting its contents.
echo "Hello, World!" > output.txtAccess script arguments using $1, $2, and so on.
#!/bin/bash
echo "First argument: $1"
echo "Second argument: $2"These arguments can be passed when running the script.
./script.sh arg1 arg2The exit status of the last command executed is stored in the special variable $?.
#!/bin/bash
ls /path/to/file
echo "Exit status: $?"This value is 0 if the command was successful, and non-zero if there was an error.
This can be also used to exit a script with a specific status.
#!/bin/bash
if [ condition ]; then
exit 0
else
exit 1
fiThis guide provides an overview of essential shell scripting elements to help you automate tasks effectively.
Sources: