A shell script is a text file that contains a sequence of commands for a Unix-based operating system. It is called a shell script because it combined a sequence of commands in a file that would otherwise have to be typed in one at a time into a single script.
#!/bin/zsh
#!/bin/bash
#!/bin/sh
A shebang is a special comment at the top of shell scripts that tells the system which shell to use when executing a file.
# This is a comment in a shell script!
name="Grant"
age=28
echo "$name is $age years old."
-eq-ne-gt - Greater than-lt - Less than-ge-le= - Equal to!= - Not equal toecho "Enter a number:"
read number
Some popular comparison operators include:
if [ $num -gt 10 ]; then
echo "The number is greater than 10"
else
echo "The number is 10 or less"
fi
if [ condition ]; then
# Code for true condition
fi
if [ condition ]; then
# Code for true condition
else
# Code for false condition
fi
if [ condition1 ]; then
# Code for condition1 true
elif [ condition2 ]; then
# Code for condition2 true
else
# Code if none of the above conditions are true
fi
fruits=("apple" "banana" "cherry")
echo "First fruit {fruits[0]}"
echo "All fruits {fruits[@]}"
# For Loop
for i in {1..5}; do
echo "Count: $i"
done
# While Loop
count=1
while [$count -le 5]; do
echo "Count: $count"
((count++))
done
greet() {
echo "Hello, $1"
}
greet "World"
Some popular comparison operators include:
$@ - All arguments$? - Exit status of the last commandecho "Script name: $0"
echo "Script name: $1"
echo "Script name: $2"
echo "Script name: $#"
mkdir new_folder
if [ $? -eq 0 ]; then
echo "Directory created successfully!"
else
echo "Failed to create directory"
fi
mkdir new_folder || { echo "Error creating directory!"; exit 1 }
name="Grant"
echo 'Hello $name' # Prints Hello $name
echo "Hello $name" # Prints Hello Grant
trap function INT
This means to run the function when I receive Ctrl+C (SIGINT).
trap function EXIT
This means to run the function whenever the shell script exits.
bash -x script.sh
#!/bin/zsh
#!/bin/zsh -x
#!/bin/zsh -e
sleep 2 # waits 2 seconds before resuming
# Define color variables
RED='\e[31m'
GREEN='\e[32m'
YELLOW='\e[33m'
BLUE='\e[34m'
ENDCOLOR='\e[0m' # Clear text formatting
# Use variables in your script
echo -e "${GREEN}Success:${ENDCOLOR} The operation completed successfully."
echo -e "${YELLOW}Warning:${ENDCOLOR} Disk space is getting low."
echo -e "${RED}Error:${ENDCOLOR} Process failed."
touch shell_script.sh
#!/bin/zsh
echo "This is a new shell script!"
echo "Creating a directory..."
mkdir shell_script_example
cd shell_script_example
echo "Adding a file..."
touch number_list.txt
echo "1234567890" >> number_list.txt
echo "Script executed successfully!"
ls -l shell_script.sh
chmod +x shell_script.sh
./shell_script.sh