Results 1 to 4 of 4
Hello friends,
First off, sorry for a novice question. I have found the following in a bash scripting tutorial. Could you please help me to understand what that means?
# ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
- 01-07-2013 #1Just Joined!
- Join Date
- Jan 2013
- Posts
- 2
Link filedescriptor to stdin
Hello friends,
First off, sorry for a novice question. I have found the following in a bash scripting tutorial. Could you please help me to understand what that means?
# Link filedescriptor 10 with stdin
exec 10<&0
# stdin replaced with a file supplied as a first argument
exec < $1
let count=0
- 01-07-2013 #2Just Joined!
- Join Date
- May 2011
- Location
- Brazil
- Posts
- 21
Hi rhanik,
Can you please provide the complete bash script?
For very file created on Linux a file descriptor is created too. It identifies the file inside the OS. Linux has 3 standard file descriptors:
- 0 stdin = Standard input
- 1 stdout = Standard output
- 2 stderr = Standard error
It seems that your script is sending every input to the file descriptor 10.
The second statement is using the argument number 1 that was passed to the script as the standard input.
The let command evaluates the expression count=0 returning TRUE or FALSE.
With the entire script we can figure out the real meaning of the statements
Thanks,
Best Regards,
Leví
- 01-07-2013 #3Just Joined!
- Join Date
- Jan 2013
- Posts
- 2
@Levi_Silva
purpose of the script is to read file into bash array:
#!/bin/bash
# Declare array
declare -a ARRAY
# Link filedescriptor 10 with stdin
exec 10<&0
# stdin replaced with a file supplied as a first argument
exec < $1
let count=0
while read LINE; do
ARRAY[$count]=$LINE
((count++))
done
echo Number of elements: ${#ARRAY[@]}
# echo array's content
echo ${ARRAY[@]}
# restore stdin from filedescriptor 10
# and close filedescriptor 10
exec 0<&10 10<&-
- 01-07-2013 #4Just Joined!
- Join Date
- May 2011
- Location
- Brazil
- Posts
- 21
Hey rhanik,
As said, Bash has 3 file descriptors pre-defined:
- 0 -> stdin = Keyboard
- 1 -> stdout = Monitor
- 2 -> stderr = Monitor
When you execute a script it will read the commands from the standard input that is the keyboard.
As you said, the script purpose is to read the file content, LINE by LINE, and stores it at internal variable ARRAY.
You can do that using another commands but I believe that the tutorial meant to show the use of exec bash command.
First you save the traditional stdin: exec 10<&0.
After, changes the stdin to the first received argument: exec < $1
Now every read command will read information from the argument $1 and not from keyboard.
After script reads from a file, it restores the stdin from the saved file descriptor number 10.
In this point your script can back read from keyboard.
In the end of the script, insert the following:
echo -n "Enter data "
read a # Reading from normal stdin.
echo $a
Thanks,
BR,
Leví


Reply With Quote
