init 0
Published in
2 min readAug 8, 2024
conditions, loops, functions, error handling, IOs, arrays, strings, debug
Shell Scripting Tips and Guidelines
1. Basic Script Structure
#!/bin/bash
# This is a comment
echo "Hello, World!"
2. Variables
# Assigning a variable
MY_VAR="Hello"
# Accessing a variable
echo $MY_VAR
# Using variables in strings
echo "The value of MY_VAR is: ${MY_VAR}"
3. Conditional Statements
# If-else statement
if [ "$MY_VAR" == "Hello" ]; then
echo "Greeting is Hello"
else
echo "Greeting is not Hello"
fi
# Case statement
case $1 in
start)
echo "Starting";;
stop)
echo "Stopping";;
*)
echo "Usage: $0 {start|stop}"
exit 1
esac
4. Loops
# For loop
for i in {1..5}; do
echo "Looping ... number $i"
done
# While loop
COUNTER=1
while [ $COUNTER -le 5 ]; do
echo "Count: $COUNTER"
COUNTER=$((COUNTER + 1))
done
5. Functions
my_function() {
echo "This is a function"
}
# Calling a function
my_function
6. Error Handling
# Exit script on error
set -e
# Function to handle errors
error_exit() {
echo "$1" 1>&2
exit 1
}
# Example usage
cp /nonexistentfile /tmp || error_exit "File copy failed!"
7. Input and Output
# Reading input from the user
read -p "Enter your name: " NAME
echo "Hello, $NAME!"
# Redirecting output to a file
echo "This is a log message" >> mylogfile.log
# Redirecting error output
ls /nonexistent 2>> errors.log
8. Using Arrays
# Declaring an array
MY_ARRAY=("one" "two" "three")
# Accessing array elements
echo ${MY_ARRAY[0]}
echo ${MY_ARRAY[@]}
# Adding elements to an array
MY_ARRAY+=("four")
# Looping through an array
for element in "${MY_ARRAY[@]}"; do
echo $element
done
9. String Manipulation
# String length
MY_STRING="Hello, World!"
echo ${#MY_STRING}
# Substring
echo ${MY_STRING:7:5}
# Replacing a substring
echo ${MY_STRING/World/Bash}
10. Debugging Scripts
# Enabling debugging mode
set -x
# Disabling debugging mode
set +x
Best Practices
- Use comments to explain your code.
- Follow naming conventions for variables and functions.
- Check for errors after running commands.
- Use functions to organize and reuse code.
- Test your scripts in different environments.
- Use version control (e.g., git) to manage your script libraries.
- Avoid hardcoding values; use variables and configuration files instead.
- Handle user input carefully to avoid injection attacks.