Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
3_4_format.doc
Скачиваний:
0
Добавлен:
01.05.2025
Размер:
94.21 Кб
Скачать

2.5 Redirecting stdin using exec

Consider a few files containing examples of the possible use of the system call exec.

Redirecting stdin using 'exec'.

#! /bin/bash

# redirecting stdin using 'exec' .

exec 6 <& 0 # Link file descriptor. # 6 from the standard input

(stdin).

# Saving stdin.

exec <data-file #stdin replaced by file "data - file"

read a1 # Reads the first line of "data-file".

read a2 # Read the second line of "data-file."

echo

echo "The following lines were read from the file."

echo "---------------------------------------------------------"

echo $a1

echo $a2

echo; echo; echo

exec 0<& 6 6<&-

#Rehabilitating stdin from decr. #6, where it was previously saved,

#+ and descr. #6 closing ( 6<&- ) relisting it for another processes.

#

# <&6 6<&- gives the same result.

echo -n “Enter string ”

read b1 #Now function “reed” receives data from ordinary stdin.

echo “String received from stdin.”

echo “-----------------------------------”

echo “b1 = $b1”

echo

exit 0

Similarly, the construction exec> fdename redirects output to stdout in specified file. After , the whole output from teams, which usually sent to stdout, now output in this file.

#! /bin/bash

#reassign-stdout.sh

LOGFILE=logfile.txt

Exec 6>&1 # Bind descr. #6 with stdout.

# Saving stdout.

Exec > $LOGFILE # Stdout is changed by file “logfile.txt”.

#-------------------------------------------------------------------------------------------------------#

# All enter from commands in this block is writing into the file

&LOGFILE.

Echo -n “Logfile: ”

Date

Echo “-----------------------------------------------”

Echo

Echo “Enter command \”ls - al\””

Echo

ls -al

echo; echo

echo “Output of commad \”df\””

echo

df

#--------------------------------------------------------------------------------------------------------#

exec 1>&6 6>&- #Restore stdout and close descr. #6.

echo

echo “== stdout restored in default value == ”

echo

ls -al

echo

exit 0

3 Key Questions

  1. What is I / O flow?

  2. What is necessary to redirect I / O streams?

  3. Operators to redirect input / output.

  4. What channel?

  5. What do you know the standard streams and how do they work?

4 Homework

  1. Examine the key provisions.

  2. Written reply to the control questions.

  3. Prepare for the lab assignments.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]