Sie sind auf Seite 1von 16

Chapter 1 answers

Jump to: navigation, search Chapter 1 Challenges Home Chapter 2: Getting Started With Shell Programming What is the shell? A type of computer user interface ( see What is Linux Shell ) Q. Decide whether the following sentence is true or false: 1. True 2. False ( Kernel [ OS ] manages files and data. ) 3. False ( see above ) 4. True 5. False 6. True 7. True 8. True 9. True 10. True 11. True 12. False 13. True 14. True 15. True 16. True 17. True 18. True Write a command names, which can display the files to the terminal.
ls

Write a command to list details of all files ending in '.perl' in reverse time order.
ls -r *.perl

Write a command to list your running programs.


ps

OR
top

OR
top -u username

Write a command to list files waiting to be printed.


lpq

Write a command to delete 3 files called file1.txt, file2.txt, and data1.txt.


rm file1.txt file2.txt data1.txt

OR
rm file{1,2}.txt data1.txt

Write a command to creates a new sub-directory called 'foo' in /tmp.


mkdir /tmp/foo

Write a command to delete the directory called 'foo'.


rmdir foo

Write a command to read all ls command options.


man ls

Chapter 2 answers
Jump to: navigation, search Chapter 2 Challenges Home Chapter 3:The Shell Variables and Environment Write a program that prints your favorite movie name. It should print director name on the next line.
#!/bin/bash echo "The Shawshank Redemption" echo "Frank Darabont"

Write a shell script that prints out your name and waits for the user to press the [Enter] key before the script ends.
#!/bin/bash echo "Vivek Gite" read -p "Press [Enter] key to continue..." fakeEnterKey

List 10 builtin and external commands. A: Use type command and which command to find out builtin and external commands. cd to /etc/init.d and view various system init scripts.
cd /etc/init.d ls vi ssh

Chapter 3 answers
Jump to: navigation, search Chapter 3 Challenges Home Chapter 4: Conditionals Execution (Decision Making) 1. Make a backup of existing variable called PS1 to OLDPS1. Set PS1 to '$'. Reset your prompt using OLDPS1 variable.
OLDPS1=$PS1 PS1='$' date clear PS1=$OLDPS1 date

2. Customize your bash prompt by setting PS1 variable to 'I Love Scripting '.
PS1='I Love Scripting ' date clear

3. Edit your $HOME/.bashrc file and set your new PS1 variable.
vi $HOME/.bashrc

PS1='I Love Scripting '

Save and close the file.

4. Create a list of legal and illegal bash variable names. Describe why each is either legal or illegal.
# legal variables backup="/nas0" _datasrc="/dev/st0" # illegal variables # white space _ data src="/dev/st0"

See Rules for Naming variable name

5. Write a command to display the environment.


printenv

6. Write a shell script that allows a user to enter his or her top three ice cream flavors. Your script should then print out the name of all three flavors.
#!/bin/bash read -p "Enter your three ice cream flavors : " ice1 ice2 ice3 echo "Thanks $USER!" echo "1# ${ice1}" echo "2# ${ice2}" echo "#3 ${ice3}"

7. Write a shell script that allows a user to enter any Internet domain name (host name such as www.cyberciti.biz). Your script should than print out the IP address of the Internet domain name.
#!/bin/bash # Version 1 read -p "Enter any Internet domain name : " domainname host "${domainname}"

OR
#!/bin/bash # Version 2 read -p "Enter any Internet domain name : " domainname host "${domainname}" | grep 'has address'

8. Write a shell script that allows a user to enter any existing file name. The program should then copy file to /tmp directory.
#!/bin/bash # Version 1 (blind copy) read -p "Enter any file name : " filename cp $filename /tmp

OR
#!/bin/bash # Version 2 (first check for $filename and than copy it, else display an error message) read -p "Enter any file name : " filename # if file exists, than copy it if [ -f "${filename}" ] then cp -v "$filename" /tmp else echo "$0: $filename not found." fi

9. Write a shell script that allows a user to enter directory name. The program should then create directory name in /tmp directory.
#!/bin/bash # Version 1 (blind "mkdir directory" command) read -p "Enter any directory name : " directory mkdir "/tmp/${directory}"

OR
#!/bin/bash # Version 2 (Make sure dir does not exist, else display an error message) read -p "Enter any directory name : " directory # Make sure dir does not exits if [ ! -d "/tmp/${directory}" ] then mkdir -v "/tmp/${directory}" else echo "$0: /tmp/${directory} already exits." fi

OR
#!/bin/bash # Version 3 # Make sure dir does not exist, else display an error message # Use variables BASE="/tmp" read -p "Enter any directory name : " directory

# create a path mydir="${BASE}/${directory}" # Make sure dir does not exits if [ ! -d "${mydir}" ] then mkdir -v "${mydir}" else echo "$0: ${mydir} already exists." fi

10. Write a shell script that allows a user to enter three file names. The program should then copy all files to USB pen.
#!/bin/bash # Version 1 PEN="/media/usb" read -p "Enter three file names : " f1 f2 f3 cp -v "$f1" "$f2" "$f3" $PEN

OR
#!/bin/bash # Version 2 # Make sure file exits and usb pen is mounted at $PEN # Set path PEN="/media/usb" read -p "Enter three file names : " f1 f2 f3 # Make sure pen drive exits else die [ ! -d "$PEN" ] && { echo "$0: USB pen drive not found at $PEN"; exit 1; } # Make sure pen drive is mounted else die if grep -wq "$PEN" /etc/mtab then # Make copy only if file exists, else display [ -f "$f1" ] && cp -v "$f1" $PEN || echo "$0: [ -f "$f2" ] && cp -v "$f2" $PEN || echo "$0: [ -f "$f3" ] && cp -v "$f3" $PEN || echo "$0: else echo "$0: USB pen is not mounted at $PEN." fi

an error $f1 not found." $f2 not found." $f3 not found."

11. Write a simple shell script where the user enters a pizza parlor bill total. Your script should then display a 10 percent tip.
#!/bin/bash # Version 1

clear echo "*************************" echo "*** Joes Pizza Parlor ***" echo "*************************" echo echo "Today is $(date)" echo read -p "Enter a pizza parlor bill : " bill tip=$(echo "scale=2; (${bill}*10) / 100" | bc -l) total=$(echo "scale=2; $tip + $bill" | bc -l) echo "Pizza bill : $bill" echo "Tip (10%) : ${tip}" echo "--------------------------" echo "Total : ${total}" echo "--------------------------"

12. Write a simple calculator program that allows user to enter two numeric values and operand as follows. The program should then print out the sum of two numbers. Make sure it works according to entered operand.
#!/bin/bash read -p "Enter two values : " a b read -p "Enter operand ( +, -, /, *) : " op ans=$(( $a $op $b )) echo "$a $op $b = $ans"

Chapter 3 Challenges

Chapter 4 answers
Jump to: navigation, search Chapter 4 Challenges Home Chapter 5: Bash Loops Decide whether the following sentence is true or false: 1. 2. 3. 4. 5. 6. True True False False True True

Write a shell script that display one of ten unique fortune cookie message, at random each it is run.
#!/bin/bash # Genarate a number (random number) between 1 and 10 r=$(( $RANDOM%10+0 )) # Quotes author name author="\t --Bhagavad Gita." # Store cookies or quotes in an array array=( "Neither in this world nor elsewhere is there any happiness in store for him who always doubts." "Hell has three gates: lust, anger, and greed." "Sever the ignorant doubt in your heart with the sword of self-knowledge. Observe your discipline. Arise." "Delusion arises from anger. The mind is bewildered by delusion. Reasoning is destroyed when the mind is bewildered. One falls down when reasoning is destroyed." "One gradually attains tranquillity of mind by keeping the mind fully absorbed in the Self by means of a well-trained intellect, and thinking of nothing else." "The power of God is with you at all times; through the activities of mind, senses, breathing, and emotions; and is constantly doing all the work using you as a mere instrument." "One who has control over the mind is tranquil in heat and cold, in pleasure and pain, and in honor and dishonor; and is ever steadfast with the Supreme Self" "The wise sees knowledge and action as one; they see truly." "The mind acts like an enemy for those who do not control it." "Perform your obligatory duty, because action is indeed better than inaction." ) # Display a random message echo echo ${array[$r]} echo -e "$author" echo

Chapter 4 Challenges

Chapter 5 answers
Jump to: navigation, search Chapter 5 Challenges Home Chapter 6: Shell Redirection Decide whether the following sentence is true or false: 1. False 2. False 3. False

4. 5. 6. 7.

False True True True

Write a menu driven script using the select statement to print calories for food items such as pizza, burger, Salad, Pasta etc.

Write a shell script that, given a file name as the argument will count vowels, blank spaces, characters, number of line and symbols.
#!/bin/bash file=$1 v=0 if [ $# -ne 1 ] then echo "$0 fileName" exit 1 fi if [ ! -f $file ] then echo "$file not a file" exit 2 fi while read -n 1 c do l=$(echo $c | tr [:upper:] [:lower:]) [[ "$l" == "a" || "$l" == "e" || "$l" == "i" || "$l" == "o" || "$l" == "u" ]] && (( v++ )) done < $file echo echo echo echo "Vowels : $v" "Characters : $(cat $file | wc -c)" "Blank lines : $(grep -c '^$' $file)" "Lines : $(cat $file|wc -l )"

Write a shell script that, given a file name as the argument will count English language articles such As 'A', 'An' and 'The'.
#!/bin/bash file=$1 a=0 if [ $# -ne 1 ] then echo "$0 fileName" exit 1

fi if [ ! -f $file ] then echo "$file not a file" exit 2 fi while read line do l=$(echo $line | tr [:upper:] [:lower:]) for word in $l do [[ $word == "a" || $word == "an" || $word == "the" ]] && ((a++)) done done < $file echo "articles : $a"

Write a shell script that, given a file name as the argument will write the even numbered line to a file with name evenfile and odd numbered lines in a text file called oddfile.
#!/bin/bash file=$1 counter=0 if [ $# -ne 1 ] then echo "$0 fileName" exit 1 fi if [ ! -f $file ] then echo "$file not a file" exit 2 fi while read line do ((counter++)) EvenNo=$(( counter%2 )) if [ $EvenNo -eq 0 ] then echo $line >> evenfile else echo $line >> oddfile fi done < $file

Write a shell script to monitor Linux server disk space using a while loop. Send an email alert when percentage of used disk space is >= 90%.
#!/bin/bash ADMIN="me@somewher.com" # set alert level 90% is default ALERT=90 df -H | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output; do #echo $output usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1 ) partition=$(echo $output | awk '{ print $2 }' ) if [ $usep -ge $ALERT ]; then echo "Running out of space \"$partition ($usep%)\" on $(hostname) as on $ (date)" | mail -s "Alert: Almost out of disk space $usep" $ADMIN fi done

Write a shell script to determine if an input number is a palindrome or not. A palindromic number is a number where the digits, with decimal representation usually assumed, are the same read backwards, for example, 58285.
#!/bin/bash echo -n "Enter number : " read n # store single digit sd=0 # store number in reverse order rev="" # store original number on=$n while [ $n -gt 0 ] do sd=$(( $n % 10 )) # get n=$(( $n / 10 )) # get # store previous number rev=$( echo ${rev}${sd} done

Remainder next digit and current digit in reverse )

if [ $on -eq $rev ]; then echo "Number is palindrome" else echo "Number is NOT palindrome" fi

Write a shell program to read a number *such as 123) and find the sum of digits (1+2+3=6).

#!/bin/bash #store the no num=$1 #store the value of sum sum=0 if [ $# -ne 1 ] then echo "$0 number" exit 1 fi while [ $num -gt 0 ] do digit=$(( num%10 )) num=$(( num/10 )) sum=$(( digit+sum )) done echo "Sum of digits = $sum"

Write a shell program to read a number and display reverse the number. For example, 123 should be printed as as 321.
#!/bin/bash #store the no num=$1 #store the reverse number rev=0 if [ $# -ne 1 ] then echo "$0 number" exit 1 fi while [ $num -gt 0 ] do digit=$(( num%10 )) num=$(( num/10 )) rev=$(( digit + rev*10 )) done echo "Reverse of number = $rev"

Write the shell program which produces a report from the output of ls -l in the following format:
file1 file2 [DIR] test/

Total Total Total Total

regular files : 7 directories : 4 symbolic links : 0 size of regular files : 2940

#!/bin/bash #copying the out of ls -l command to a file ls -l > /tmp/tmp.tmp #initilizing values sum=0 dir=0 file=0 link=0 #reading the file while read line do #getting the first character of each line to check the type of file read -n 1 c <<< $line #checking if the file is a directory or not if [ $c == "d" ] then ((dir++)) echo "[DIR] ${line}/" | cut -d" " --fields="1 9" >> /tmp/dir.tmp elif [ $c == "-" ] #true if the file is a regular file then ((file++)) echo $line | cut -d" " -f8 >> /tmp/file.tmp elif [ $c == "l" ] then ((link++)) fi #true if the file is a symbolic link

size=$( echo $line | cut -d" " -f5 ) #getting the size of the file sum=$(( sum+size )) #adding the size of all the files done < /tmp/tmp.tmp cat /tmp/file.tmp #output the name of all the files cat /tmp/dir.tmp #output the name of all the directory echo echo echo echo "Total "Total "Total "Total regular files = $file" directories = $dir" symbolic links = $link" size of regular file = $size"

#removing the temporary files rm /tmp/file.tmp rm /tmp/dir.tmp rm /tmp/tmp.tmp

Write a shell script that will count the number of files in each of your sub-directories using the for loop.
#!/bin/bash START=$HOME # change your directory to command line if passed # otherwise use home directory [ $# -eq 1 ] && START=$1 if [ ! -d $START ] then echo "$START not a directory!" exit 1 fi # use find command to get all subdirs name in DIRS variable DIRS=$(find "$START" -type d) # loop thought each dir to get the number of files in each of subdir for d in $DIRS do [ "$d" != "." -a "$d" != ".." ] && echo "$d dirctory has $(ls -l $d | wc -l) files" done

Write a shell script that accepts two directory names as arguments and deletes those files in the first directory which are similarly named in the second directory.
#!/bin/bash SRC="$1" DST="$2" if [ $# -ne 2 ] then echo "$(basename $0) dir1 dir2" exit 1 fi if [ ! -d $SRC ] then echo "Directory $SRC does not exists!" exit 2 fi if [ ! -d $DST ] then echo "Directory $DST does not exists!" exit 2 fi for f in $DST/* do #echo Processing $f if [ -f $f ]

then tFile="$SRC/$(basename $f)" if [ -f $tFile ] then echo -n "Deleting $tFile..." /bin/rm $tFile [ $? -eq 0 ] && echo "done" || echo "failed" fi done fi

Write a shell script to search for no password entries in /etc/passwd and lock all accounts.
#!/bin/bash # Shell script for search for no password entries and lock all accounts # Set your email ADMINEMAIL="admin@somewhere.com" ### Do not change anything below ### #LOG File LOG="/root/nopassword.lock.log" STATUS=0 TMPFILE="/tmp/null.mail.$$" echo "-------------------------------------------------------" >>$LOG echo "Host: $(hostname), Run date: $(date)" >> $LOG echo "-------------------------------------------------------" >>$LOG # get all user names USERS="$(cut -d: -f 1 /etc/passwd)" # display message echo "Searching for null password..." for u in $USERS do # find out if password is set or not (null password) passwd -S $u | grep -Ew "NP" >/dev/null if [ $? -eq 0 ]; then # if so echo "$u" >> $LOG passwd -l $u #lock account STATUS=1 #update status so that we can send an email fi done echo "========================================================" >>$LOG if [ $STATUS -eq 1 ]; then echo "Please see $LOG file and all account with no password are locked!" >$TMPFILE echo "-- $(basename $0) script" >>$TMPFILE mail -s "Account with no password found and locked" "$ADMINEMAIL" < $TMPFILE # rm -f $TMPFILE fi

Write a shell program to read two numbers and display all the odd numbers between those two numbers.
#!/bin/bash # Shell program to read two numbers and display all the odd echo -n "Enter first number : " read n1 echo -n "Enter second number : " read n2 if [ $n2 -gt $n1 ]; then for(( i=$n1; i<=$n2; i++ )) do # see if it is odd or even number test=$(( $i % 2 )) if [ $test -ne 0 ]; then echo $i fi done else echo "$n2 must be greater than $n1, try again..." fi

Chapter 5 Challenges

Das könnte Ihnen auch gefallen