Shell scripting cheatsheet
SED :
it is used to replace a word
Replace a word in a file:sed 's/old_word/new_word/' file.txt
Replace all occurrences of a word in a file:sed 's/old_word/new_word/g' file.txt
Delete lines matching a pattern:sed '/pattern/d' file.txt
AWK:
Print specific columns from a CSV file:awk -F ',' '{print $1, $3}' file.csv
Calculate the sum of a column in a numeric file: awk '{sum += $1} END {print sum}' file.txt
Filter lines based on a condition:awk '$3 > 50 {print $1, $3}' file.txt
Shebang: The shebang, also known as a hashbang, is the first line of a script and specifies the interpreter to use. For example, #!/bin/bash
Variables: Variables store data for later use. $name. To declare a variable as global, use the export keyword.
Command substitution: For example, files=$(ls) stores the output of the ls command in the files variable.
Control structures:
if-else: Conditionally execute code based on a condition. It has the form:
if condition; then
# code to execute if condition is true
else
# code to execute if condition is false
fi
for loop: Iterate over a list of items. It has the form:
for item in list; do
# code to execute for each item
done
while loop: Repeatedly execute code as long as a condition is true. It has the form:
while condition; do
# code to execute while condition is true
done
case statement: Perform different actions based on the value of a variable. It has the form:
case variable in
pattern1)
# code to execute for pattern1
;;
pattern2)
# code to execute for pattern2
;;
*)
# code to execute for other cases
;;
esac
Functions: Functions allow you to define reusable blocks of code. They are declared using the function keyword or simply by their name followed by parentheses. For example:
function greet() {
echo "Hello, $1!"
}
greet "John"
Input/output: The read command is used to read input, and echo or printf are used to display output.
Conditional expressions: -eq (equal), -ne (not equal), -lt (less than), -gt (greater than), -z (empty string)
Redirecting input/output: The command < input.txt reads input from input.txt, and command > output.txt redirects output to output.txt.
$* -> treats all the charcaters in a single quotes as one
$@ -> it uses delimeter example " hello world" foo bar : it treats as strings "hello world", "foo", and "bar
write one function and then call the functions
mytest(){
local name=$1;
echo hello, $name;
}
mytest world
1) Write a shell script to accept the name from name and age from the user and display that back to the user.
Ans)
#!/bin/bash
# Prompt the user to enter their name
echo "Enter your name:"
read name
# Prompt the user to enter their age
echo "Enter your age:"
read age
# Display the name and age back to the user
echo "Name: $name"
echo "Age: $age"
2) Write a shell script to accept a file name from the user and make a copy of that file. Ans)
#!/bin/bash
# Prompt the user to enter a file name
echo "Enter the name of the file you want to copy:"
read filename
# Check if the file exists
if [ -f "$filename" ]; then
# Generate a unique copy filename
copy_filename="${filename}_copy"
# Make a copy of the file
cp "$filename" "$copy_filename"
echo "File copied successfully. New file name: $copy_filename"
else
echo "File does not exist."
fi
3) Write a shell script to accept file name from the user and display the contents of file. If the file doesn't exist then try curbing the error and display a user friendly error to user. Ans)
#!/bin/bash
# Prompt the user to enter a file name
echo "Enter the name of the file:"
read filename
# Check if the file exists
if [ -f "$filename" ]; then
# Read and display the contents of the file
echo "Contents of $filename:"
cat "$filename"
else
echo "Error: File '$filename' does not exist."
fi
4) Write a shell script to accept a file name from user and check whether its an ordinary file or a directory. In case of file show the contents of file and if itís a directory show number of files in that directory.
Ans)
#!/bin/bash
# Prompt the user to enter a file name
echo "Enter the name of the file or directory:"
read filename
# Check if the specified path exists
if [ -e "$filename" ]; then
# Check if it's a file
if [ -f "$filename" ]; then
echo "Contents of $filename:"
cat "$filename"
# Check if it's a directory
elif [ -d "$filename" ]; then
num_files=$(ls -1 "$filename" | wc -l)
echo "Number of files in $filename: $num_files"
else
echo "Error: '$filename' is neither a file nor a directory."
fi
else
echo "Error: Path '$filename' does not exist."
fi
5) Write a shell script to accept a file name from user. Check whether file has all the permissions if not assign the respective permissions to that file.
Ans)
#!/bin/bash
# Prompt the user to enter a file name
echo "Enter the name of the file:"
read filename
# Check if the file exists
if [ -f "$filename" ]; then
# Check if all permissions are set
if [ -r "$filename" ] && [ -w "$filename" ] && [ -x "$filename" ]; then
echo "File '$filename' already has all permissions."
else
# Assign missing permissions
if [ ! -r "$filename" ]; then
chmod +r "$filename"
echo "Read permission added to '$filename'."
fi
if [ ! -w "$filename" ]; then
chmod +w "$filename"
echo "Write permission added to '$filename'."
fi
if [ ! -x "$filename" ]; then
chmod +x "$filename"
echo "Execute permission added to '$filename'."
fi
fi
else
echo "Error: File '$filename' does not exist."
fi
6) Write a shell script to accept a file name from the user and sort the file. If the file doesn't exist curb the error message and show the user-friendly message.
Ans)
#!/bin/bash
# Prompt the user to enter a file name
echo "Enter the name of the file:"
read filename
# Check if the file exists
if [ -f "$filename" ]; then
# Sort the file
sorted_filename="${filename}_sorted"
sort "$filename" > "$sorted_filename"
echo "File sorted successfully. Sorted file: $sorted_filename"
else
echo "Error: File '$filename' does not exist."
fi
it is used to replace a word
Replace a word in a file:sed 's/old_word/new_word/' file.txt
Replace all occurrences of a word in a file:sed 's/old_word/new_word/g' file.txt
Delete lines matching a pattern:sed '/pattern/d' file.txt
AWK:
Print specific columns from a CSV file:awk -F ',' '{print $1, $3}' file.csv
Calculate the sum of a column in a numeric file: awk '{sum += $1} END {print sum}' file.txt
Filter lines based on a condition:awk '$3 > 50 {print $1, $3}' file.txt
Shebang: The shebang, also known as a hashbang, is the first line of a script and specifies the interpreter to use. For example, #!/bin/bash
Variables: Variables store data for later use. $name. To declare a variable as global, use the export keyword.
Command substitution: For example, files=$(ls) stores the output of the ls command in the files variable.
Control structures:
if-else: Conditionally execute code based on a condition. It has the form:
if condition; then
# code to execute if condition is true
else
# code to execute if condition is false
fi
for loop: Iterate over a list of items. It has the form:
for item in list; do
# code to execute for each item
done
while loop: Repeatedly execute code as long as a condition is true. It has the form:
while condition; do
# code to execute while condition is true
done
case statement: Perform different actions based on the value of a variable. It has the form:
case variable in
pattern1)
# code to execute for pattern1
;;
pattern2)
# code to execute for pattern2
;;
*)
# code to execute for other cases
;;
esac
Functions: Functions allow you to define reusable blocks of code. They are declared using the function keyword or simply by their name followed by parentheses. For example:
function greet() {
echo "Hello, $1!"
}
greet "John"
Input/output: The read command is used to read input, and echo or printf are used to display output.
Conditional expressions: -eq (equal), -ne (not equal), -lt (less than), -gt (greater than), -z (empty string)
Redirecting input/output: The command < input.txt reads input from input.txt, and command > output.txt redirects output to output.txt.
$* -> treats all the charcaters in a single quotes as one
$@ -> it uses delimeter example " hello world" foo bar : it treats as strings "hello world", "foo", and "bar
write one function and then call the functions
mytest(){
local name=$1;
echo hello, $name;
}
mytest world
1) Write a shell script to accept the name from name and age from the user and display that back to the user.
Ans)
#!/bin/bash
# Prompt the user to enter their name
echo "Enter your name:"
read name
# Prompt the user to enter their age
echo "Enter your age:"
read age
# Display the name and age back to the user
echo "Name: $name"
echo "Age: $age"
2) Write a shell script to accept a file name from the user and make a copy of that file. Ans)
#!/bin/bash
# Prompt the user to enter a file name
echo "Enter the name of the file you want to copy:"
read filename
# Check if the file exists
if [ -f "$filename" ]; then
# Generate a unique copy filename
copy_filename="${filename}_copy"
# Make a copy of the file
cp "$filename" "$copy_filename"
echo "File copied successfully. New file name: $copy_filename"
else
echo "File does not exist."
fi
3) Write a shell script to accept file name from the user and display the contents of file. If the file doesn't exist then try curbing the error and display a user friendly error to user. Ans)
#!/bin/bash
# Prompt the user to enter a file name
echo "Enter the name of the file:"
read filename
# Check if the file exists
if [ -f "$filename" ]; then
# Read and display the contents of the file
echo "Contents of $filename:"
cat "$filename"
else
echo "Error: File '$filename' does not exist."
fi
4) Write a shell script to accept a file name from user and check whether its an ordinary file or a directory. In case of file show the contents of file and if itís a directory show number of files in that directory.
Ans)
#!/bin/bash
# Prompt the user to enter a file name
echo "Enter the name of the file or directory:"
read filename
# Check if the specified path exists
if [ -e "$filename" ]; then
# Check if it's a file
if [ -f "$filename" ]; then
echo "Contents of $filename:"
cat "$filename"
# Check if it's a directory
elif [ -d "$filename" ]; then
num_files=$(ls -1 "$filename" | wc -l)
echo "Number of files in $filename: $num_files"
else
echo "Error: '$filename' is neither a file nor a directory."
fi
else
echo "Error: Path '$filename' does not exist."
fi
5) Write a shell script to accept a file name from user. Check whether file has all the permissions if not assign the respective permissions to that file.
Ans)
#!/bin/bash
# Prompt the user to enter a file name
echo "Enter the name of the file:"
read filename
# Check if the file exists
if [ -f "$filename" ]; then
# Check if all permissions are set
if [ -r "$filename" ] && [ -w "$filename" ] && [ -x "$filename" ]; then
echo "File '$filename' already has all permissions."
else
# Assign missing permissions
if [ ! -r "$filename" ]; then
chmod +r "$filename"
echo "Read permission added to '$filename'."
fi
if [ ! -w "$filename" ]; then
chmod +w "$filename"
echo "Write permission added to '$filename'."
fi
if [ ! -x "$filename" ]; then
chmod +x "$filename"
echo "Execute permission added to '$filename'."
fi
fi
else
echo "Error: File '$filename' does not exist."
fi
6) Write a shell script to accept a file name from the user and sort the file. If the file doesn't exist curb the error message and show the user-friendly message.
Ans)
#!/bin/bash
# Prompt the user to enter a file name
echo "Enter the name of the file:"
read filename
# Check if the file exists
if [ -f "$filename" ]; then
# Sort the file
sorted_filename="${filename}_sorted"
sort "$filename" > "$sorted_filename"
echo "File sorted successfully. Sorted file: $sorted_filename"
else
echo "Error: File '$filename' does not exist."
fi
Comments
Post a Comment