1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
A and b both
C
d.
E and f
12.
13.
14,
15.
16.
17.
18. (a)
(b)
19.
20.
#!/bin/bash
# Function to display the first or last part of a file
display_file_part() {
local file="$1"
local lines="$2"
if [ "$operation" == "head" ]; then
# Display the first part of the file
echo "Head:"
head -n "$lines" "$file"
elif [ "$operation" == "tail" ]; then
# Display the last part of the file
echo "Tail:"
tail -n "$lines" "$file"
fi
}
# Default values
lines=10
operation="head"
# Parse command-line options
while getopts ":n:c:" opt; do
case $opt in
n)
lines=$OPTARG
;;
c)
lines=$OPTARG
operation="tail"
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
:)
echo "Option -$OPTARG requires an argument." >&2
exit 1
;;
esac
done
# Shift the options so that $1 now refers to the file
shift "$((OPTIND-1))"
# Check if a file is provided
if [ $# -eq 0 ]; then
echo "Usage: $0 [-n lines] [-c bytes] <file>"
exit 1
fi
file="$1"
# Check if the file exists
if [ ! -e "$file" ]; then
echo "Error: File not found: $file"
exit 1
fi
# Display the requested part of the file
display_file_part "$file" "$lines"
23.
24.
25.
26.
#!/bin/bash
# Check if the user is aa10
if [ "$(logname)" = "aa10" ]; then
# Get the present working directory
current_directory=$(pwd)
# Check if the user aa10 is logged in
if who | grep -wq "aa10"; then
# Display present working directory
echo "Current Directory: $current_directory"
# Send a message to the terminal
echo "Hello aa10! How about dinner tonight? �
" > /dev/pts/$(who | awk '/aa10/{print $2}' | head -n 1)
else
# Mail a dinner proposal
echo "Hello aa10! How about dinner tonight? �
fi
fi
27.
#!/bin/bash
# Prompt user for numbers
echo "Enter numbers (enter 0 to stop):"
read -p "Enter a number: " number
# Initialize variables
logon_name=$(whoami)
lowest=$number
highest=$number
# Continue reading numbers until 0 is entered
while [ $number -ne 0 ]; do
read -p "Enter a number: " number
# Check if the entered number is 0
Please confirm your availability." | mail -s "Dinner Proposal" aa10
if [ $number -eq 0 ]; then
break
fi
# Update lowest and highest numbers
if [ $number -lt $lowest ]; then
lowest=$number
fi
if [ $number -gt $highest ]; then
highest=$number
fi
done
# Calculate difference and product
difference=$((highest - lowest))
product=$((highest * lowest))
# Display the results
echo -e "\nResults:"
echo "i. User: $logon_name"
echo "ii. Lowest number entered: $lowest"
echo "m. Highest number entered: $highest"
echo "iv. Difference between the two: $difference"
echo "V. Product of the two: $product"
28.
#!/bin/bash
# Check if the number of arguments is even
if [ $# -eq 0 ] || [ $(( $# % 2 )) -ne 0 ]; then
echo "Error: Please provide an even number of filenames for copying."
exit 1
fi
# Loop through the arguments two at a time and perform copying
for (( i=1; i<=$#; i+=2 )); do
source_file="${!i}"
destination_file="${!((i+1))}"
# Check if source file exists
if [ ! -e "$source_file" ]; then
echo "Error: Source file '$source_file' does not exist."
exit 1
fi
# Perform copying
cp "$source_file" "$destination_file"
echo "Copied '$source_file' to '$destination_file'."
done
echo "Copying completed successfully."
29.
#!/bin/bash
echo "Files with read, write, and execute permissions in the current directory:"
# Use the find command to search for files with the specified permissions
find . -maxdepth 1 -type f -perm -700 -exec basename {} \;
30.
#!/bin/bash
file="myfile"
# Check if the file exists
if [ -e "$file" ]; then
echo "File '$file' already exists."
else
# Create the file
touch "$file"
echo "File '$file' created."
fi
# Ask for confirmation to erase the file
read -p "Do you want to erase the file? (y/n): " confirmation
if [ "$confirmation" = "y" ]; then
# Erase the file
rm "$file"
echo "File '$file' erased."
else
echo "File '$file' was not erased."
Fi
31.
#!/bin/bash
# Check if two filenames are provided as arguments
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <file1> <file2>"
exit 1
fi
file1="$1"
file2="$2"
# Check if the files exist
if [ ! -e "$file1" ] || [ ! -e "$file2" ]; then
echo "Error: Both files must exist."
exit 1
fi
# Check if the contents of the files are the same
if cmp -s "$file1" "$file2"; then
# If contents are the same, delete the second file
rm "$file2"
echo "Contents are the same. Second file '$file2' deleted."
else
echo "Contents are different. No action taken."
fi
32.
#!/bin/bash
extension="new"
# Check if there are files in the current directory
if [ -n "$(ls)" ]; then
# Rename all files by adding the extension
for file in *; do
if [ -f "$file" ]; then
mv "$file" "${file%.*}.$extension"
echo "Renamed: $file -> ${file%.*}.$extension"
fi
done
echo "Extension '$extension' added to all files."
else
echo "Error: No files found in the current directory."
Fi
33.
#!/bin/bash
# Check the number of arguments
if [ "$#" -ne 1 ]; then
echo "Error: Please provide a single file as an argument."
exit 1
fi
file="$1"
# Check if the file exists
if [ ! -e "$file" ]; then
echo "Error: File '$file' not found."
exit 1
fi
# Display owner's name and last update time
owner=$(stat -c "%U" "$file" 2>/dev/null)
last_update=$(stat -c "%y" "$file" 2>/dev/null)
if [ $? -eq 0 ]; then
echo "Owner: $owner"
echo "Last Update Time: $last_update"
else
echo "Error: Unable to retrieve owner and last update time for '$file'."
Fi
34.
#!/bin/bash
# Check if a number is provided as a command line argument
if [ "$#" -eq 0 ]; then
echo "Error: Please provide a number as a command line argument."
exit 1
fi
number="$1"
# Check if the input is a valid number
if ! [[ $number =~ ^[0-9]+$ ]]; then
echo "Error: Invalid input. Please provide a valid number."
exit 1
fi
# Reverse the number using rev command
reversed_number=$(echo "$number" | rev)
echo "Original Number: $number"
echo "Reversed Number: $reversed_number"
35.
#!/bin/bash
# Check if a file name is provided as a command line argument
if [ "$#" -eq 0 ]; then
echo "Error: Please provide a file name as a command line argument."
exit 1
fi
file_name="$1"
# Delete the file using rm command with quotes around the file name
rm "$file_name"
# Check the exit status of the rm command
if [ $? -eq 0 ]; then
echo "File '$file_name' deleted successfully."
else
echo "Error: Unable to delete file '$file_name'."
fi
36.
In Linux, numeric comparisons can be performed using various operators within shell scripts or directly in the command
line. Here are some common numeric comparison operators:
1. *Equal to (-eq):*
bash
if [ "$a" -eq "$b" ]; then
echo "$a is equal to $b"
fi
2. *Not equal to (-ne):*
bash
if [ "$a" -ne "$b" ]; then
echo "$a is not equal to $b"
fi
3. *Greater than (-gt):*
bash
if [ "$a" -gt "$b" ]; then
echo "$a is greater than $b"
fi
4. *Greater than or equal to (-ge):*
bash
if [ "$a" -ge "$b" ]; then
echo "$a is greater than or equal to $b"
fi
5. *Less than (-lt):*
bash
if [ "$a" -lt "$b" ]; then
echo "$a is less than $b"
fi
6. *Less than or equal to (-le):*
bash
if [ "$a" -le "$b" ]; then
echo "$a is less than or equal to $b"
fi
Here, $a and $b represent the numeric values you want to compare. These comparisons are often used in conditional
statements within shell scripts to control the flow of execution based on numeric conditions.
For direct command line usage, you can use the test command or the double square brackets [[ ... ]] construct:
bash
# Using test command
if test "$a" -eq "$b"; then
echo "$a is equal to $b"
fi
# Using double square brackets
if [[ "$a" -eq "$b" ]]; then
echo "$a is equal to $b"
fi
These examples assume that $a and $b are variables containing numeric values. Adjust the comparisons and variables
according to your specific use case.
37.
Using awk:
sum=$(awk '{ sum += $1 } END { print sum }' your_file.txt)
echo "Sum of numbers in the file: $sum"
: Using grep and awk:
sum=$(grep -oE '[0-9]+' your_file.txt | awk '{ sum += $1 } END { print sum }')
echo "Sum of numbers in the file: $sum"
Using paste and bc:
sum=$(paste -sd+ your_file.txt | bc)
echo "Sum of numbers in the file: $sum"
38.
#!/bin/bash
# Check if a filename is provided as an argument
if [ "$#" -eq 0 ]; then
echo "Error: Please provide a filename as an argument."
exit 1
fi
filename="$1"
# Use sed to delete lines with <dd> between the 5th and 7th position
sed '/^.\{4\}<dd>/,/^.\{6\}<dd>/d' "$filename" > temp_file
mv temp_file "$filename"
echo "Lines containing <dd> between the 5th and 7th position have been deleted."
39.
#!/bin/bash
# Check if a filename is provided as an argument
if [ "$#" -eq 0 ]; then
echo "Error: Please provide a filename as an argument."
exit 1
fi
filename="$1"
# Use tr to replace spaces and punctuation with newlines
# Use tr to convert everything to lowercase
# Use sort to sort the words
# Use uniq -c to count the occurrences of each unique word
# Use awk to format and print the results
tr -s '[:space:][:punct:]' '\n' < "$filename" | tr '[:upper:]' '[:lower:]' | sort | uniq -c | awk '{print "Word: " $2, " |
Occurrences: " $1}'
40
#!/bin/bash
# Use find to locate all .txt files, including those in subdirectories
# Use xargs to pass the file list to grep for counting occurrences of "Linux"
# Use wc -l to count the total number of occurrences
total_count=$(find . -type f -name "*.txt" -exec grep -o -i "Linux" {} + | wc -l)
echo "Total occurrences of 'Linux' in .txt files: $total_count".
42. #!/bin/bash
# Check if a directory path is provided as an argument
if [ -z "$1" ]; then
echo "Usage: $0 <directory>"
exit 1
fi
directory="$1"
# Check if the directory exists
if [ ! -d "$directory" ]; then
echo "Error: '$directory' is not a valid directory."
exit 1
fi
# Count the number of files and subdirectories
file_count=$(find "$directory" -maxdepth 1 -type f | wc -l)
dir_count=$(find "$directory" -maxdepth 1 -type d | wc -l)
# Print the results
echo "Number of files in '$directory': $file_count"
echo "Number of subdirectories in '$directory':
$dir_count"
43 #!/bin/bash
# Check if a number is provided as an argument
if [ -z "$1" ]; then
echo "Usage: $0 <number>"
exit 1
fi
number="$1"
# Check if the input is a valid number
if ! [[ $number =~ ^[0-9]+$ ]]; then
echo "Error: '$number' is not a valid number."
exit 1
fi
# Reverse the number
reverse=""
len=${#number}
for (( i=$len-1; i>=0; i-- )); do
reverse="${reverse}${number:$i:1}"
done
# Print the reversed number
echo "Reverse of $number is: $reverse"
44. #!/bin/bash
# Check if at least one string is provided
if [ $# -eq 0 ]; then
echo "Usage: $0 <string1> <string2> ..."
exit 1
fi
# Reverse the order of strings
reversed_list=("$@")
reversed_list=("${reversed_list[@]:(-1)}")
# Reverse each string in the list
for ((i=${#reversed_list[@]}-1; i>=0; i--)); do
original="${reversed_list[i]}"
reversed=""
len=${#original}
for (( j=$len-1; j>=0; j-- )); do
reversed="${reversed}${original:$j:1}"
done
reversed_list[i]="$reversed"
done
# Print the reversed list
echo "Original List: $@"
echo "Reversed List with Reversed Strings: ${reversed_list[@]}"
45.
#!/bin/bash
# Check if a directory path is provided as an argument
if [ -z "$1" ]; then
echo "Usage: $0 <directory>"
exit 1
fi
directory="$1"
# Check if the directory exists
if [ ! -d "$directory" ]; then
echo "Error: '$directory' is not a valid directory."
exit 1
fi
# Find the newest file based on modification time
newest_file=$(find "$directory" -type f -printf '%T@ %p\n' | sort -n | tail -n 1 | cut -d ' ' -f 2)
# Check if any files were found
if [ -z "$newest_file" ]; then
echo "No files found in '$directory'."
else
echo "Newest file in '$directory': $newest_file"
fi.
46.
#!/bin/bash
# Check if an argument is provided
if [ -z "$1" ]; then
echo "Enter Either R, W, or X:"
read -r permission
else
permission="$1"
fi
# Validate the provided argument
if [[ ! "$permission" =~ ^[RWX]$ ]]; then
echo -e "\aInvalid argument. Please enter either R, W, or X."
exit 1
fi
# Find and display ordinary files based on the specified permission
case "$permission" in
R)
permission_flag="-read"
;;
W)
permission_flag="-write"
;;
X)
permission_flag="-execute"
;;
esac
# List ordinary files with the specified permission
find . -type f -perm /u=$permission_flag -exec basename {} \;
[10:13 PM, 12/18/2023] Nishant Garg Ip Cdac: 48. Write a shell script for renaming each file in the directory such that it
will have the current shell PID as an extension. The shell script should ensure that the directories do not get renamed.
[10:13 PM, 12/18/2023] Nishant Garg Ip Cdac: #!/bin/bash
# Check if a directory path is provided as an argument
if [ -z "$1" ]; then
echo "Usage: $0 <directory>"
exit 1
fi
directory="$1"
# Check if the directory exists
if [ ! -d "$directory" ]; then
echo "Error: '$directory' is not a valid directory."
exit 1
fi
# Navigate to the specified directory
cd "$directory" || exit 1
# Rename files in the directory
for file in *; do
if [ -f "$file" ]; then
new_name="${file%.}_$$.${file##.}"
mv "$file" "$new_name"
echo "Renamed: $file to $new_name"
fi
done
47.
#!/bin/bash
# Check if LOGNAME or UID is provided as an argument
if [ -z "$1" ]; then
echo "Usage: $0 <LOGNAME or UID>"
exit 1
fi
# Get the user's login name or UID
user_identifier="$1"
# Find the number of terminals the user is logged into
terminal_count=$(who | awk -v user="$user_identifier" '$1 == user {count++} END {print count}')
# Display the result
echo "User '$user_identifier' is logged into $terminal_count terminal(s)."
49.
#!/bin/bash
# Check if a file path is provided as an argument
if [ -z "$1" ]; then
echo "Usage: $0 <file>"
exit 1
fi
file="$1"
# Check if the file exists
if [ ! -f "$file" ]; then
echo "Error: '$file' is not a valid file."
exit 1
fi
# Extract unique words and count occurrences
word_count=$(tr -s '[:space:]' '\n' < "$file" | tr -d '[:punct:]' | tr '[:upper:]' '[:lower:]' | sort | uniq -c)
# Display the result
echo "Unique words and their occurrences in '$file':"
echo "$word_count"
50.
#!/bin/bash
# Check if a directory path is provided as an argument
if [ -z "$1" ]; then
echo "Usage: $0 <directory>"
exit 1
fi
directory="$1"
# Check if the directory exists
if [ ! -d "$directory" ]; then
echo "Error: '$directory' is not a valid directory."
exit 1
fi
# Count occurrences of the word "Linux" in all ".txt" files
total_count=$(grep -roh -w -E --include="*.txt" "$directory" -e "Linux" | wc -l)
# Display the result
echo "Total occurrences of 'Linux' in '*.txt' files: $total_count"
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )