Shorts question
12.Write a shell to reverse a string
#!/bin/bash
read -p "Enter a string: " input
# Reverse the string
reversed=$(echo "$input" | rev)
echo "Reversed string: $reversed"
13 Display elements of an array
#!/bin/bash
# Correct array initialization
arr=("apple" "banana" "cherry" "date")
# Print array elements
echo "Array elements:"
for element in "${arr[@]}"; do
echo "$element"
done
14.Write a shell script to reverse array elements.
#!/bin/bash
arr=("apple" "banana" "cherry" "date")
# Function to reverse the array
reversed=()
for ((i=${#arr[@]}-1; i>=0; i--)); do
reversed+=("${arr[i]}")
done
echo "Reversed array elements:"
for element in "${reversed[@]}"; do
echo "$element"
done
15.Demonstrate the use of $$,$0,$*,$@
#!/bin/bash
# $$ - Process ID of the script
echo "Process ID of this script: $$"
# $0 - The name of the script
echo "Name of the script: $0"
# $* - All the arguments as a single string
echo "All arguments as a single string: $*"
# $@ - All the arguments, each quoted separately
echo "All arguments as separate strings: $@"
# Loop through $*
echo "Looping through \$*:"
for arg in $*; do
echo "$arg"
done
# Loop through $@
echo "Looping through \$@:"
for arg in "$@"; do
echo "$arg"
done
20.Write a shell script to delete all text files from the directory
#!/bin/bash
# Specify the directory (or use the current directory)
dir=${1:-.}
# Confirm deletion with the user
read -p "Are you sure you want to delete all .txt files in the directory $dir? (y/n): " confirm
if [[ $confirm == [yY] ]]; then
# Delete all .txt files in the specified directory
rm -f "$dir"/*.txt
echo "All .txt files deleted from $dir."
else
echo "Operation canceled."
fi
19.Write a shell script to change case of string.
#!/bin/bash
# Read input from the user
read -p "Enter a string: " input
# Prompt for case conversion choice
echo "Choose an option:"
echo "1. Convert to UPPERCASE"
echo "2. Convert to lowercase"
read -p "Enter choice (1 or 2): " choice
# Change case based on user choice
if [ "$choice" -eq 1 ]; then
output=$(echo "$input" | tr '[:lower:]' '[:upper:]')
echo "Converted to UPPERCASE: $output"
elif [ "$choice" -eq 2 ]; then
output=$(echo "$input" | tr '[:upper:]' '[:lower:]')
echo "Converted to lowercase: $output"
else
echo "Invalid choice. Please enter 1 or 2."
exit 1
fi
18.Write a shell script to delete all empty lines from any file
#!/bin/bash
# Check if a file name was provided
if [ -z "$1" ]; then
echo "Usage: $0 filename"
exit 1
fi
# Remove empty lines from the specified file
sed -i '/^$/d' "$1"
echo "Empty lines removed from $1."
Comments
Post a Comment