Skip to content

Unix Shell Scripting Exercise 1

Rushikesh edited this page Oct 13, 2018 · 1 revision

Q-1. Presumably, What Could Be The Reason That The Command Start Giving The Following Error Message? --bash: cat: Command not found Ans.

The command not found error occurs when either the PATH variable is corrupt or have some issue in configuration.

Hence, it’ll throw the error message as mentioned in the question.

Q-2. How Can We Pass Arguments To A Script In Linux? And How To Access These Arguments From Within The Script? Ans.

We can write a bash script that can accept arguments from the command line in the following manner.

$ ./scriptName "arg1" "arg2"..."argn" To access these arguments, we can use the positional parameters ($1 to $9) in the script. Each parameter corresponds to the position of the argument on the command line.

The first argument is read by the shell into the parameter $1, the second argument into $2, and so on. After $9, start enclosing the arguments in brackets like ${10}, ${11}, and ${12}.

Some shells don’t support the above method. In that case, to access parameters with numbers greater than 9, you can use the shift command. It moves the parameter list to the left.

$1 is lost, $2 becomes $1, $3 becomes $2, and so on. The inaccessible 10th parameter becomes $9 and becomes accessible.

Let’s check out an example for clarity.

#!/bin/bash

Call this script with at least 3 parameters

echo "First parameter is $1" echo "Second parameter is $2" echo "Third parameter is $3" exit 0 Upon execution, the test script will yield the following output.

sh parameters.sh 50 51 52

First parameter is 50 Second parameter is 51 Third parameter is 52

Q-3. What Is The Difference Between $* And $@? Ans.

$@ treats each quoted arguments as separate arguments but $* considers the entire set of positional parameters as a single string.

Q-4. What Is The Command To Display The List Of Files In A Directory? Ans.

The following command displays the list of files in a directory.

$ ls -lrt | grep ^-

Q-5. Write A Shell Script To Display The Last Updated File Or The Newest File In A Directory? Ans.

Following is the test script to list the most recently changed file.

#!/bin/bash

ls -lrt | grep ^- | awk 'END{print $NF}'

Q-6. Write A Shell Script To Get The Current Date, Time, Username And Current Working Directory. Ans.

Let’s create a file named <stats.sh> and add the following code in it.

#!/bin/bash echo "Hello, $LOGNAME" echo "Current date is 'date'" echo "User is 'who i am'" echo "Current directory 'pwd'" First of all, assign the execute permission for the script and then execute it. It’ll display the required information.

Q-7. Write A Shell Script That Adds An Extension “.New” To All The Files In A Directory. Ans.

Please use the following script to change all the files in a directory to a “.new” extension. Kindly make sure to supply the directory name as an argument while running the test script.

#!/bin/bash dir=$1 for file in ls $1/* do mv $file $file.new done

Q-8. Write A Shell Script To Print A Number In Reverse Order. It Should Support The Following Requirements. The script should accept the input from the command line. If you don’t input any data, then display an error message to execute the script correctly. Ans.

Let’s first, jot down the steps involved in the test script.

  1. Suppose the input number is n.
  2. Set reverse and single digit to 0 (i.e. rev=0, sd=0).
  3. The expression (n % 10) will give the single left most digit i.e. sd.
  4. To reverse the number, use this expression <rev * 10 + sd>.
  5. Decrease the input number (n) by 1.
  6. If n is greater than 0, then go to step no. 3. Else, execute the step no. 7.
  7. Print the result.

The script code is as follows.

#!/bin/bash if [ $# -ne 1 ] then echo "Please provide the correct input in the below format." echo "Usage: $0 number" echo " This script will reverse the given number." echo " For eg. $0 1234, will print 4321" exit 1 fi

n=$1 rev=0 sd=0

while [ $n -gt 0 ] do sd=expr $n % 10 rev=expr $rev \* 10 + $sd n=expr $n / 10 done echo "Reverse number is $rev" There are two ways in which we can run the above script.

Instance 1: If there is no input, you will get the following output.

$ ./testscript.sh

Please provide the correct input in the below format. Usage: ./testscript.sh number This script will reverse the given number. For eg. ./testscript.sh 1234, will print 4321 Instance 2: When the input is available in the command line Argument, you will get the following output.

$ ./testscript.sh 12345 Reverse number is 54321

Q-9. How Will You Delete A File Which Has Special Characters In Its File Name? Ans.

In Linux or Unix-like system, you may come across file names including the following special characters, white spaces, backslashes and more.

-- ; & $ ? * Bash shell considers most of the above special characters as commands. Thus, the “rm” command may not be able to delete such files. The simplest way to delete files having special characters in its name is by using the inode number.

Step-1. The <-i> option of command displays the index number (inode) of each file.

$ ls -li 9966571 -rw-r--r-- 1 techbeamers users 0 Sep 16 10:05 Step-2. Use the command given below to delete the file, if it has inode number such as 9966571.

$ find . -inum 9966571 -exec rm -i {} ;

Q-10. How To Ask For Input In A Shell Script From The Terminal? Ans:

In Linux, we can use the command to take input from the user. It reads data from the terminal as the user enters it from the keyboard. And stores into a variable.

Let’s see a sample test script featuring the command.

#!/bin/bash echo ‘Please enter your name’ read name echo “My Name is $name” Upon running the above script, it’ll prompt for the name and assigns the input value to the variable .

$ ./test.sh Please enter your name TechBeamers My Name is TechBeamers

Q-11. How Can We Perform Numeric Comparisons In Linux? Ans.

The test command can perform various types of numeric comparison using the following operators.

Syntax: INTEGER1 -eq INTEGER2 Description: INTEGER1 is equal to INTEGER2 Example Code:

#!/bin/bash read -p "Please enter number 20 from the keyboard : " n if test $n -eq 20 then echo "Thanks for entering the number 20."

else

echo “You are not following my instructions.” fi 2. Syntax: INTEGER1 -ge INTEGER2 Description: INTEGER1 is greater than or equal to INTEGER2 Example Code:

#!/bin/bash read -p "Enter a number >= 10 : " n if test $n -ge 10 then echo "Correct value entered."

else

echo “You are not following my instructions.”

fi 3. Syntax: INTEGER1 -gt INTEGER2 Description: INTEGER1 is greater than INTEGER2 Example Code:

#!/bin/bash read -p "Enter number > 20 : " n if test $n -gt 20 then echo "$n is greater than 20."

else

echo “You are not following my instructions.”

fi 4. Syntax: INTEGER1 -le INTEGER2 Description: INTEGER1 is less than or equal to INTEGER2 Example Code:

#!/bin/bash read -p "Enter backup level : " n if test $n -le 6 then echo "Incremental backup requested." fi if test $n -eq 7 then echo "Full backup requested."

else

echo “You are not following my instructions.”

fi 5. Syntax: INTEGER1 -lt INTEGER2 Description: INTEGER1 is less than INTEGER2 Example Code:

#!/bin/bash read -p "Do not enter negative number here : " n

if test $n -lt 0 then echo "You entered a negative number!!" else echo “You are not following my instructions.” fi 6. Syntax: INTEGER1 -ne INTEGER2 Description: INTEGER1 is not equal to INTEGER2 Example Code:

#!/bin/bash read -p "Do not enter number 5 here : " n if test $n -ne 5 then echo "Thanks for not entering number 5."

else

echo “You are not following my instructions.”

fi

Q-12. What Is The Syntax For Different Types Of Loops Available In Shell Scripting? Ans.

Following are the loops supported in shell scripting.

  1. . #!/bin/bash

for i in $( ls ); do echo item: $i done 2. . #!/bin/bash

COUNT=0 while [ $COUNT -lt 10 ]; do echo The counter value is $COUNT let COUNT+=1 done 3. . #!/bin/bash

COUNT=20 until [ $COUNT -lt 10 ]; do echo The counter value is $COUNT let COUNT-=1 done 4. . #!/bin/bash

PS3="Select a week day (1-7): " select i in mon tue wed thur fri sat sun exit do case $i in mon) echo "Monday";; tue) echo "Tuesday";; wed) echo "Wednesday";; thur) echo "Thursday";; fri) echo "Friday";; sat) echo "Saturday";; sun) echo "Sunday";; exit) exit;; esac done

Q-13. How Will You Find The Sum Of All Numbers In A File In Linux? Ans.

Following is the script which computes the sum of all numbers stored in a file.

#!/bin/bash

awk '{x+=$0}END{print x}' filename

Q-14. Write A Shell Script To Delete The Lines Containing A Word

If It Appears Between The 5th And 7th Position? Ans.

Let’s take a fixed width file as:

ff1 ff2 ff3 sds dd fd sd ss ew dd dd se The expected output after script execution is.

ff1 ff2 ff3 sd ss ew The test script to do the expected task is as follows.

for i in 'cat test.txt' do j = 'expr length $i' if ( "$j" == 5 then v = 'echo $i | grep dd' if [ "$v" != "" ] then echo $v sed -i "s/$v/lalat/g" test.txt fi fi done

Q-15. Write A Shell Script To Find Out The Unique Words In A File And Also Count The Occurrence Of Each Of These Words. We Can Say That File Under Consideration Contains Many Lines, And Each Line Has Multiple Words. Ans.

$ cat animal.txt tiger bear elephant tiger bear bear Following test script/command will count the unique words.

$ awk '{for(i=1;i<=NF;i++)a[$i]++;}END{for(i in a){print i, a[i];}}' animal.txt

Output: elephant 1 bear 3 tiger 2

Q-16. Write A Shell Script To Get The Total Count Of The Word “Linux” In All The “.Txt” Files And Also Across Files Present In Subdirectories. Ans.

The following is the test script/command which recursively searches for the “.txt” files and returns the total occurrences of a word .

$ find . -name *.txt -exec grep -c Linux '{}' ; | awk '{x+=$0;}END{print x}'

Q-17. Write A Shell Script To Validate Password Strength. Here Are A Few Assumptions For The Password String. Length – minimum of 8 characters. Contain both alphabet and number. Include both the small and capital case letters. If the password doesn’t comply to any of the above conditions, then the script should report it as a .

Ans.

#Password Validation Script echo "Enter your password" read password len="${#password}"

if test $len -ge 8 ; then echo "$password" | grep -q [0-9] if test $? -eq 0 ; then echo "$password" | grep -q [A-Z] if test $? -eq 0 ; then echo "$password" | grep -q [a-z]
if test $? -eq 0 ; then echo "Strong Password" else echo "Weak Password -> Should include a lower case letter." fi else echo "Weak Password -> Should include a capital case letter." fi else echo "Weak Password -> Should use numbers in your password."
fi else echo "Weak Password -> Password length should have at least 8 characters." fi

Q-18. Write A Shell Script To Print The Count Of Files And Subdirectories In The Specified Directory. Ans.

#!/bin/bash

if [ -d "$@" ]; then echo "Files found: $(find "$@" -type f | wc -l)" echo "Folders found: $(find "$@" -type d | wc -l)" else echo "[ERROR] Please retry with a folder." exit 1 fi

Q-19. Write A Shell Script To Print The Reverse Of An Input Number. Ans.

#!/bin/bash

if [ $# -eq 1 ]; then if [ $1 -gt 0 ]; then num=$1 revNum=0 while [ $num -ne 0 ] do testnum=$(( $num % 10 )) revNum=$(( $revNum * 10 + $testnum )) num=$(( $num / 10 )) done echo "Reverse Number: $revNum of $1" else echo "Input is less than 0, retry with a different number." fi else echo "ERROR: Retry with one parameter." fi

Q-20. Write A Shell Script To Reverse The List Of Strings And Reverse Each String Further In The List. Ans.

#!/bin/bash

if [ $# != 0 ]; then len=echo $@ | wc -c len=expr $len - 1 strrev="" while test $len -gt 0 do strrev1=echo $@ | cut -c$len strrev=$strrev$strrev1 len=expr $len - 1 done echo $strrev else echo "ERROR: Retry with a list of strings." fi