1 Basic Shell Programs (Assignment - 1) Solution Manual a.Listing files and directories. ls command is used to show all the files and directories. b. Showing, creating and concatenating files. Cat command: $ cat info.txt --------- displays the contents of the file info.txt $ cat >data.txt ----------------------for creating files, after entering some text data in the file, press ctrl+d(it denotes the EOF character) $ cat info.txt data.txt >all_data.txt-------------------the contents of the two file info.txt and data.txt are stored in the third file all_data.txt(if all_data.txt contains something then it will be overwritten). If we want to append data in the third file all_data.txt then we have use $ cat info.txt data.txt >>all_data.txt c. Coping files, Renaming files and deleting files. cp: copying files The cp command is used to copy files, create duplicate copy of ordinary files in another name. $ cp srcfile desfile [example: $ cp delta1.txt delta2.txt--------- this makes a copy of the file delta1.txt in delta2.txt, if a file by the destination filename already exists then it sis overwritten with the contents of the source file without any warning. We can use an option in the last mentioned command that will copy interactively prompt the user before overwriting, $ cp -i delta1.txt delta2.txt. mv:renaming files The mv(move) command changes the name of the file.Basically, using the mv command, the file is removed from its current location and is copied to another location. $ mv oldname newname------ this command moves or renames the file oldname to newname. Example: $ mv delta_force.txt Gamma_dyne.txt---- renames the file delta_force.txt to Gamma_dyne.txt rm: Removing files This command removes one or more ordinary files from a directory. The file is removed by deleting its pointer in the appropriate directory. In this way the link between that filename and the physical file is broken and hence the file is no longer accessed. Example: $ rm remarks.txt ----- this command deletes the file remarks.txt. $ rm –i programs.doc ----- this command prompts us for confirmation before removing the file. The prompt is generally: rm: remove programs.doc (yes/no)?---- to delete the file, we have type y followed by the enter key(n in case we do not want to delete the file). d. Making directories ,changing directories, Removing directories. mkdir: Making directories The mkdir command is used to create one or more directories. Example: $ mkdir courses -----this command creates a directory by name courses under the current directory. $ mkdir courses faculty placement ----- this creates 3 directories by names courses, faculty and placement. (Note:-If the directory name already exists, the mkdir command aborts and does not overwrite the the existing directory.For example if we give $ mkdir courses---- since a directory with the name courses already exists, this command will generate an error: mkdir: can’t make directory courses.) The option –p stands for parent and is used for creating a parent directory in the given path. For example:
2 $ mkdir –p kgec/dept/cse ---- this command creates a directory; kgec within which a sub-directory: dept and under that a sub-diectory: cse. There are several situations in which the directory is not created and mkdir aborts with the following error: mkdir: unable to make directory. The reasons are : 1. A directory with the same name already exists. 2. An ordinary file by the same name already exists in the current directory. 3. The user doesn’t have read-write permission to create files and directories in the current directory. cd:changing directories We use the cd comma nd to change to any directory in the current file-system. $ cd pathname Here, pathname is either an absolute or relative path name for the desired target directory. Example: $ cd /home/kgec/cse ----- this command takes us to the directory cse(that is assumed to exists in the current directory). When we directly give the directory name(without using ‘/’ as prefix), it means that it is a relative path(i.e., a path related to the current directory). The aforementioned path is an absolute path. $ cd .. ----------- this command takes us to the parent directory. (Note: .. refers to the parent directory). We can reach to our home directory from any other directory by simply typing the cd command without any argument. We don’t specify our home directory as an argument, because our shell always knows that name of our home directory. rmdir: removing directories This command is used to remove a directory. $ rmdir [-p] pathname --- here the –p is used to remove the parent directory if it is empty. (NOTE: the rmdir command cannt remove a directory until it is empty.) Example: $ rmdir cse ----- to remove the directory cse(but if the cse directory is not empty then the following error is displayed: rmdir: cse: Directory not empty). We can delete more than one directory by using the following single command. $ rmdir cse ece it ----------- it deletes the 3 directories if those are empty. To delete directory chain(/directory_1/directory_2/directory_3/directory_4) we can use the –p option. For example: rmdir –p /directory_1/directory_2/directory_3/directory_4 ----- it deletes all the 4 directories, if they are empty. Remember, we cannot use rmdir command to remove our current working directory. If we wish to remove our working directory, we have to first come out of it. e. Make the following directory tree:- KGEC |--------------------|-------------------------|----------------------|----------------------| CSE IT ECE ME EE | |----------First_Year |----------Second_Year |----------Third_Year |----------Fourth_Year The following commands are used to create the above directory tree.
3 1. Write a Shell script that will display the date, time, username and current directory. Solution: To write the script use vi editor: vi display.sh (NOTE: Shell script files ends with .sh extensions, here display is the file name.) # This script displays the date, time, username and current directory. echo "Date and time is:" date echo echo "Your username is: `whoami`" echo "Your current directory is: `pwd`" The first two lines beginning with a hash (#) are comments and are not interpreted by the shell. Use comments to document your shell script; you will be surprised how easy it is to forget what your own programs do! Echo command is used to print something on the screen. The backquotes (`) around the command whoami illustrate the use of command substitution. To execute: $ sh display.sh 2. Write a Shell script that will display the current working shell. Solution: # To display the current working Shell echo "Hello!!!" echo "your current working shell is: `echo $SHELL`" 3. Write a Shell script that will display information regarding the users who are logged in along with their column headings. Solution: 4. Write a Shell script that will take some command line arguments and displays the name of the shell script file, total number of arguments and the value of those arguments. Solution: # To the name of the shell script file, total number of arguments and the # value of those arguments
4 echo "Name of the shell file is : `echo $0`" echo "Total number of command line arguments passed : `echo $#`" echo "Arguments are : `echo $*`" 5. Write a Shell script that will take a name as command line arguments and displays the following: Input: sh program_6.sh Anirban Output: Hello Anirban! Welcome to UNIX. Solution: 6. Write a simple shell script myscript.sh that takes a path of a directory as a command line argument and list all files and folders inside the given directory. Run the script as: sh myscript.sh /cse/sb2/os_course/week_4/docs Solution: # Takes a directory path input and display its contents printf "Entered directory: %sn " $1 echo "Contents of the directory:" echo “====================================================” dir $1 echo “====================================================” 7. Write a Shell script that will take two numbers as command line arguments and displays their sum, difference, product and division. Solution: # take two numbers as command line arguments and # displays their sum,difference,product & division(don’t give 2nd argument as ZERO) sum=`expr $1 + $2` printf "%s + %s = %sn" $1 $2 $sum diff=`expr $1 - $2` printf "%s - %s = %sn" $1 $2 $diff prod=`expr $1 * $2` printf "%s * %s = %sn" $1 $2 $prod div=`expr $1 $2` printf "%s %s = %sn" $1 $2 $div 8. Write a Shell script that will display the shell’s PID. Solution: # Displays the PID of Shell echo PID of shell `echo $$` 9. Write a Shell script that will display the exit status of the last program to exit (generally programs return a 0 upon success ). Solution: # Displays the Exit status of last program executed in shell echo Exit status of last program `echo $?` 10. Write a Shell script that will display the current username. Solution: # Displays the current username echo Current Username:`echo $USERNAME` # YOU CAN ALSO USE: echo $LOGNAME 11. Write a Shell script that will take username as argument and displays whether he/she is logged in or not. Solution: if [ "$LOGNAME" = $1 ] then
5 printf "%s is logged in" $1 else printf "%s is not currently logged in." $1 fi NOTE: You can think of the [] operator as a form of the test command(you can also use test "$LOGNAME" = $1 ). But, one very important note -- there must be a space to the inside of each of the brackets. This is easy to forget or mistype. But, it is quite critical. 12. Modify the program 5 by using a switch-case that will take arguments in the following form: sh program_10.sh 2 + 3 Result: 5 sh program_10.sh 10 - 2 Result: 8 sh program_10.sh 10 / 2 Result: 5 sh program_10.sh 2 * 3 Result: 6 sh program_10.sh 2 # 3 Unknown Operation Solution: case "$2" in "+") ans=`expr $1 + $3` printf "%d %s %d = %dn" $1 $2 $3 $ans ;; "-") ans=`expr $1 - $3` printf "%d %s %d = %dn" $1 $2 $3 $ans ;; "*") ans=`expr "$1 * $3"` printf "%d %s %d = %dn" $1 $2 $3 $ans ;; "/") ans=`expr $1 / $3` printf "%d %s %d = %dn" $1 $2 $3 $ans ;; # Notice this: the default case is a simple * *) printf "Unknown Operationn" ;; esac 13. Write a shell script using switch case that displays the week day(MONDAY as 1) taking only an integer as input(1 to 7). Example: sh program_11.sh 2 Output: Day is TUESDAY Solution: case "$1" in "1") printf "Day is MONDAYn" ;; "2") printf "Day is TUESDAYn" ;; "3") printf "Day is WEDNESDAYn" ;; "4") printf "Day is THRUSDAYn" ;; "5") printf "Day is FRIDAYn" ;; "6") printf "Day is SATURDAYn" ;; "7") printf "Day is SUNDAYn" ;; *) printf "INVALID DAY NUMBER.ENTER BETWEEN 1-7" ;; esac

Basic shell programs assignment 1_solution_manual

  • 1.
    1 Basic Shell Programs(Assignment - 1) Solution Manual a.Listing files and directories. ls command is used to show all the files and directories. b. Showing, creating and concatenating files. Cat command: $ cat info.txt --------- displays the contents of the file info.txt $ cat >data.txt ----------------------for creating files, after entering some text data in the file, press ctrl+d(it denotes the EOF character) $ cat info.txt data.txt >all_data.txt-------------------the contents of the two file info.txt and data.txt are stored in the third file all_data.txt(if all_data.txt contains something then it will be overwritten). If we want to append data in the third file all_data.txt then we have use $ cat info.txt data.txt >>all_data.txt c. Coping files, Renaming files and deleting files. cp: copying files The cp command is used to copy files, create duplicate copy of ordinary files in another name. $ cp srcfile desfile [example: $ cp delta1.txt delta2.txt--------- this makes a copy of the file delta1.txt in delta2.txt, if a file by the destination filename already exists then it sis overwritten with the contents of the source file without any warning. We can use an option in the last mentioned command that will copy interactively prompt the user before overwriting, $ cp -i delta1.txt delta2.txt. mv:renaming files The mv(move) command changes the name of the file.Basically, using the mv command, the file is removed from its current location and is copied to another location. $ mv oldname newname------ this command moves or renames the file oldname to newname. Example: $ mv delta_force.txt Gamma_dyne.txt---- renames the file delta_force.txt to Gamma_dyne.txt rm: Removing files This command removes one or more ordinary files from a directory. The file is removed by deleting its pointer in the appropriate directory. In this way the link between that filename and the physical file is broken and hence the file is no longer accessed. Example: $ rm remarks.txt ----- this command deletes the file remarks.txt. $ rm –i programs.doc ----- this command prompts us for confirmation before removing the file. The prompt is generally: rm: remove programs.doc (yes/no)?---- to delete the file, we have type y followed by the enter key(n in case we do not want to delete the file). d. Making directories ,changing directories, Removing directories. mkdir: Making directories The mkdir command is used to create one or more directories. Example: $ mkdir courses -----this command creates a directory by name courses under the current directory. $ mkdir courses faculty placement ----- this creates 3 directories by names courses, faculty and placement. (Note:-If the directory name already exists, the mkdir command aborts and does not overwrite the the existing directory.For example if we give $ mkdir courses---- since a directory with the name courses already exists, this command will generate an error: mkdir: can’t make directory courses.) The option –p stands for parent and is used for creating a parent directory in the given path. For example:
  • 2.
    2 $ mkdir –pkgec/dept/cse ---- this command creates a directory; kgec within which a sub-directory: dept and under that a sub-diectory: cse. There are several situations in which the directory is not created and mkdir aborts with the following error: mkdir: unable to make directory. The reasons are : 1. A directory with the same name already exists. 2. An ordinary file by the same name already exists in the current directory. 3. The user doesn’t have read-write permission to create files and directories in the current directory. cd:changing directories We use the cd comma nd to change to any directory in the current file-system. $ cd pathname Here, pathname is either an absolute or relative path name for the desired target directory. Example: $ cd /home/kgec/cse ----- this command takes us to the directory cse(that is assumed to exists in the current directory). When we directly give the directory name(without using ‘/’ as prefix), it means that it is a relative path(i.e., a path related to the current directory). The aforementioned path is an absolute path. $ cd .. ----------- this command takes us to the parent directory. (Note: .. refers to the parent directory). We can reach to our home directory from any other directory by simply typing the cd command without any argument. We don’t specify our home directory as an argument, because our shell always knows that name of our home directory. rmdir: removing directories This command is used to remove a directory. $ rmdir [-p] pathname --- here the –p is used to remove the parent directory if it is empty. (NOTE: the rmdir command cannt remove a directory until it is empty.) Example: $ rmdir cse ----- to remove the directory cse(but if the cse directory is not empty then the following error is displayed: rmdir: cse: Directory not empty). We can delete more than one directory by using the following single command. $ rmdir cse ece it ----------- it deletes the 3 directories if those are empty. To delete directory chain(/directory_1/directory_2/directory_3/directory_4) we can use the –p option. For example: rmdir –p /directory_1/directory_2/directory_3/directory_4 ----- it deletes all the 4 directories, if they are empty. Remember, we cannot use rmdir command to remove our current working directory. If we wish to remove our working directory, we have to first come out of it. e. Make the following directory tree:- KGEC |--------------------|-------------------------|----------------------|----------------------| CSE IT ECE ME EE | |----------First_Year |----------Second_Year |----------Third_Year |----------Fourth_Year The following commands are used to create the above directory tree.
  • 3.
    3 1. Write aShell script that will display the date, time, username and current directory. Solution: To write the script use vi editor: vi display.sh (NOTE: Shell script files ends with .sh extensions, here display is the file name.) # This script displays the date, time, username and current directory. echo "Date and time is:" date echo echo "Your username is: `whoami`" echo "Your current directory is: `pwd`" The first two lines beginning with a hash (#) are comments and are not interpreted by the shell. Use comments to document your shell script; you will be surprised how easy it is to forget what your own programs do! Echo command is used to print something on the screen. The backquotes (`) around the command whoami illustrate the use of command substitution. To execute: $ sh display.sh 2. Write a Shell script that will display the current working shell. Solution: # To display the current working Shell echo "Hello!!!" echo "your current working shell is: `echo $SHELL`" 3. Write a Shell script that will display information regarding the users who are logged in along with their column headings. Solution: 4. Write a Shell script that will take some command line arguments and displays the name of the shell script file, total number of arguments and the value of those arguments. Solution: # To the name of the shell script file, total number of arguments and the # value of those arguments
  • 4.
    4 echo "Name ofthe shell file is : `echo $0`" echo "Total number of command line arguments passed : `echo $#`" echo "Arguments are : `echo $*`" 5. Write a Shell script that will take a name as command line arguments and displays the following: Input: sh program_6.sh Anirban Output: Hello Anirban! Welcome to UNIX. Solution: 6. Write a simple shell script myscript.sh that takes a path of a directory as a command line argument and list all files and folders inside the given directory. Run the script as: sh myscript.sh /cse/sb2/os_course/week_4/docs Solution: # Takes a directory path input and display its contents printf "Entered directory: %sn " $1 echo "Contents of the directory:" echo “====================================================” dir $1 echo “====================================================” 7. Write a Shell script that will take two numbers as command line arguments and displays their sum, difference, product and division. Solution: # take two numbers as command line arguments and # displays their sum,difference,product & division(don’t give 2nd argument as ZERO) sum=`expr $1 + $2` printf "%s + %s = %sn" $1 $2 $sum diff=`expr $1 - $2` printf "%s - %s = %sn" $1 $2 $diff prod=`expr $1 * $2` printf "%s * %s = %sn" $1 $2 $prod div=`expr $1 $2` printf "%s %s = %sn" $1 $2 $div 8. Write a Shell script that will display the shell’s PID. Solution: # Displays the PID of Shell echo PID of shell `echo $$` 9. Write a Shell script that will display the exit status of the last program to exit (generally programs return a 0 upon success ). Solution: # Displays the Exit status of last program executed in shell echo Exit status of last program `echo $?` 10. Write a Shell script that will display the current username. Solution: # Displays the current username echo Current Username:`echo $USERNAME` # YOU CAN ALSO USE: echo $LOGNAME 11. Write a Shell script that will take username as argument and displays whether he/she is logged in or not. Solution: if [ "$LOGNAME" = $1 ] then
  • 5.
    5 printf "%s islogged in" $1 else printf "%s is not currently logged in." $1 fi NOTE: You can think of the [] operator as a form of the test command(you can also use test "$LOGNAME" = $1 ). But, one very important note -- there must be a space to the inside of each of the brackets. This is easy to forget or mistype. But, it is quite critical. 12. Modify the program 5 by using a switch-case that will take arguments in the following form: sh program_10.sh 2 + 3 Result: 5 sh program_10.sh 10 - 2 Result: 8 sh program_10.sh 10 / 2 Result: 5 sh program_10.sh 2 * 3 Result: 6 sh program_10.sh 2 # 3 Unknown Operation Solution: case "$2" in "+") ans=`expr $1 + $3` printf "%d %s %d = %dn" $1 $2 $3 $ans ;; "-") ans=`expr $1 - $3` printf "%d %s %d = %dn" $1 $2 $3 $ans ;; "*") ans=`expr "$1 * $3"` printf "%d %s %d = %dn" $1 $2 $3 $ans ;; "/") ans=`expr $1 / $3` printf "%d %s %d = %dn" $1 $2 $3 $ans ;; # Notice this: the default case is a simple * *) printf "Unknown Operationn" ;; esac 13. Write a shell script using switch case that displays the week day(MONDAY as 1) taking only an integer as input(1 to 7). Example: sh program_11.sh 2 Output: Day is TUESDAY Solution: case "$1" in "1") printf "Day is MONDAYn" ;; "2") printf "Day is TUESDAYn" ;; "3") printf "Day is WEDNESDAYn" ;; "4") printf "Day is THRUSDAYn" ;; "5") printf "Day is FRIDAYn" ;; "6") printf "Day is SATURDAYn" ;; "7") printf "Day is SUNDAYn" ;; *) printf "INVALID DAY NUMBER.ENTER BETWEEN 1-7" ;; esac