LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash: Handling input from file and keyboard (https://www.linuxquestions.org/questions/programming-9/bash-handling-input-from-file-and-keyboard-698527/)

moo-cow 01-20-2009 12:58 AM

Bash: Handling input from file and keyboard
 
Hi!

I have this little shell script which copies file names taken from inputfile:

Code:

while read line; do
  cp -i $line something
done < inputfile

The problem is that the "-i" option of cp has no effect since stdin comes from inputfile and not from the user. Is there any way to circumvent this? I would somehow need to tell the shell to take input from the keyboard just for the cp command (?).

Thx,
moo-cow

chrism01 01-20-2009 01:12 AM

Code:

for file in `cat t3.t`
do
    cp -i $file t2.t
done

works for me.

laptop-power-battery 01-20-2009 01:27 AM

good

colucix 01-20-2009 02:22 AM

The easy way to accomplish your task is
Code:

#!/bin/bash
cp -i $(cat inputfile) dirname

using command substitution as in the example above will result in a list of files separated by spaces, since in this way the shell strips out the newline characters. The resulting command syntax is valid, provided the last argument is the name of an existing directory.

The hard way, following your example is
Code:

exec 8< inputfile
while read -u8 line
do
  cp -i $line copy
done
exec 8<&-

This will associate the input file to file descriptor 8 and the read statement will accept input from this file descriptor through option -u. In this way the standard input remains associated to the terminal. Also notice that the -i option of the cp command ask confirmation before overwriting a file only, not for each file to copy.

For other uses take in mind you can restore standard input from the terminal using exec < /dev/tty but in your case the while loop would have stopped its execution, having lost connection to the input file.

moo-cow 01-24-2009 08:21 AM

Thanks for the solutions!


All times are GMT -5. The time now is 01:12 PM.