Читаем 100 Shell Programs in Unix полностью

56. Write a shell script that takes a command-line argument and reports whether it is a directory, a file, or something else.

$vi prg56

clear for name

do

if test -d $name

then

echo $name is a directory

elif test -f $name

then

echo $name is a file

else

echo I don\’t know what $name is

fi

done

Sample Run

$sh prg56 mnt

mnt is a directory

$sh prg56 emp.dat

emp.dat is a file

57. Write a shell script that asks for the capital of India and repeats the question until the user gets it right. Enter capital in small letters.

$vi prg57

clear

echo What is the capital of India

read ans

while test $ans != delhi

do

echo No, that\’s not it. Try again.

read ans

done

echo That is correct.

Sample Run

$sh prg57

What is the capital of India

delhi

That is correct.

$sh prg57

What is the capital of India

mumbai

No, that’s not it. Try again.

58. Write a number-guessing script so that it uses a numeric comparison. It tells whether an incorrect guess is high or low.

$vi prg58

clear

echo I\’m thinking of a number between 1 and 50.

echo Guess it and earn my approval.

read guess

until test $guess -eq 33

do

if test $guess -gt 33

then

echo Too high! Guess again.

else

echo Too low! Guess again.

fi

read guess

done

echo Well done!

Sample Run

$sh prg58

I’m thinking of a number between 1 and 50.

Guess it and earn my approval.

10

Too low! Guess again.

20

Too low! Guess again.

25

Too low! Guess again.

30

Too low! Guess again.

35

Too high! Guess again.

40

Too high! Guess again.

50

Too high! Guess again.

32

Too low! Guess again.

33

Well done!

59. Write a shell script that accepts the user into the Wheeler Club if his or her weight is less than 80 pounds or more than 250 pounds.

$vi prg59

clear

echo Greetings., What is your weight\?

read weight

if test $weight -lt 80 -o $weight -gt 250

then

echo Welcome to the Wheeler Club!

else

echo You must work to further distinguish yourself.

fi

Sample Run

$sh prg59

Greetings., What is your weight?

55

Welcome to the Wheeler Club!

$sh prg59

Greetings., What is your weight?

70

Welcome to the Wheeler Club!

$sh prg59

Greetings., What is your weight?

90

You must work to further distinguish yourself.

$sh prg59

Greetings., What is your weight?

270

Welcome to the Wheeler Club!

60. How will you copy a file “abc.doc” present in current directory to a directory “abc2” present in the parent directory?

Steps-

$mkdir abc1

$mkdir abc2

$cd abc1

$touch abc.doc

$cp abc.doc ../abc2

To check file is copied or not

$cd $ls abc

Output is

abc.doc

61. Write a shell script to search a file in current directory.

$vi prg61

clear

echo Enter a file name to search

read fn

ls | grep $fn>/dev/null

if [$? -eq 0]

then

echo The file $fn is present in the current directory.

else

echo The file $fn is not present in the current directory.

fi

Sample Run

$sh prg61

Enter a file name to search

abc.doc

The file abc.doc is not present in the current directory.

$sh prg61

Enter a file name to search

a

The file a is present in the current directory.

62. Write a shell script to display a three digit number in English words.

$vi prg62

clear

echo Enter the three digit Number

read num

a=‘expr $num % 10’

b=‘expr $num / 10’

c=‘expr $b % 10’

d=‘expr $b / 10’

set $d $c $a

for arg in $*

do

case $arg in

1) echo One ;;

2) echo Two ;;

3) echo Three ;;

4) echo Four ;;

5) echo Five ;;

6) echo Six ;;

7) echo Seven ;

8) echo Eight ;;

9) echo Nine ;;

0) echo Zero ;;

esac

done

Sample Run

$sh prg62

Enter the three digit Number

123

One

Two

Three

63. To find number of files in Present Working Directory.

$vi prg63

clear

echo Present Working Directory is:

pwd      # to display the present working directory

echo Number of files is:

pwd | ls |wc -l

Sample Run

$sh prg63

Present Working Directory is:

/root

Number of files is:

8

64. To display distance in different units.

$vi prg64

clear

echo Input distance in kilometers

read a

met=‘expr $a \* 1000’

cm=‘expr $met \* 100’

inch=‘echo $cm / 2.54 | bc’

feet=‘echo $inch / 12 |bc’

echo The distance in meters is $met meters

echo The distance in centimeters is $cm cm

echo The distance in inches is $inch inches

Перейти на страницу:

Похожие книги

Компьютерные сети. 6-е изд.
Компьютерные сети. 6-е изд.

Перед вами шестое издание самой авторитетной книги по современным сетевым технологиям, написанное признанным экспертом Эндрю Таненбаумом в соавторстве со специалистом компании Google Дэвидом Уэзероллом и профессором Чикагского университета Ником Фимстером. Первая версия этого классического труда появилась на свет в далеком 1980 году, и с тех пор каждое издание книги неизменно становилось бестселлером. В книге последовательно изложены основные концепции, определяющие современное состояние компьютерных сетей и тенденции их развития. Авторы подробно объясняют устройство и принципы работы аппаратного и программного обеспечения, рассматривают все аспекты и уровни организации сетей — от физического до прикладного. Изложение теоретических принципов дополняется яркими, показательными примерами функционирования интернета и компьютерных сетей различного типа. Большое внимание уделяется сетевой безопасности. Шестое издание полностью переработано с учетом изменений, произошедших в сфере сетевых технологий за последние годы, и, в частности, освещает такие технологии, как DOCSIS, 4G и 5G, беспроводные сети стандарта 802.11ax, 100-гигабитные сети Ethernet, интернет вещей, современные транспортные протоколы CUBIC TCP, QUIC и BBR, программно-конфигурируемые сети и многое другое.

Дэвид Уэзеролл , Ник Фимстер , Эндрю Таненбаум

Учебные пособия, самоучители