Practice questions:
1. Write a function to print green 0K and red FAILED, and determine whether there is a parameter. If it exists, it will be 0k, and if it does not exist, it will be FAILED.
#!/bin/bash
function print_result ( ) {
if [ $# -eq 0 ] ; then
echo -e "\033 [0;31mFAILED\033 [0m"
else
echo -e "\033 [0;32m0K\033 [0m"
fi
}
print_result
print_result param1
2. Write a function to determine whether there are no positional parameters. If there are no parameters, an error will be prompted.
#!/bin/bash
function check_arg ( ) {
if [ $# -eq 0 ] ; then
echo "Error: No arguments provided."
else
echo "Arguments provided."
fi
}
check_arg
check_arg param1
3. Write a function to implement two numbers as parameters and return the maximum value
#!/bin/bash
function max_num ( ) {
if [ $1 -gt $2 ] ; then
echo $1
else
echo $2
fi
}
max_num 10 20
max_num 30 20
4. Write a function to implement two integer bit parameters and calculate addition, subtraction, multiplication and division.
#!/bin/bash
function math_operation ( ) {
echo "Addition: $(( $1 + $2 )) "
echo "Subtraction: $(( $1 - $2 )) "
echo "Multiplication: $(( $1 * $2 )) "
if [ $2 -eq 0 ] ; then
echo "Cannot divide by 0."
else
echo "Division: $(( $1 / $2 )) "
fi
}
math_operation 10 5
math_operation 20 0
5. Assign each line of the /etc/shadow file as an element to the array
#!/bin/bash
declare -a shadow_arr = ( )
while read line; do
shadow_arr += ( "$line " )
done < /etc/shadow
echo "shadow_arr: ${shadow_arr[ @] } "
6. Use an associative array to count the number of different types of shells used by users in the file /etc/passwd
#!/bin/bash
declare -A shell_counts = ( )
while read line; do
shell = $( echo $line | awk -F':' '{print $NF}' )
(( shell_counts["$shell"]++ ))
done < /etc/passwd
for key in "${
! shell_counts[ @] } " ; do
echo "$key : ${shell_counts[ $key] } "
done
7. Use an associative array to count the number of files in a specified directory by extension
#!/bin/bash
declare -A file_counts = ( )
dir_path = "/path/to/dir"
for file_path in $dir_path /*; do
file_name = $( basename "$file_path " )
extension = "${file_name## *.} "
(( file_counts["$extension"]++ ))
done
for key in "${
! file_counts[ @] } " ; do
echo "$key : ${file_counts[ $key] } "
done