1

How do I use the file redirected to the standard input of a bash script?

$ script.sh  < file_to_use_in_script

what do I have to put in my script, so that I can write the filename in a variable from this input, without knowing the pathname beforehand.

FILENAME=$file_to_use_in_script
0

2 Answers 2

1

You can use the filename /dev/stdin. Make sure to only read it once.

$ cat myscript                                                               
#!/bin/bash                                                                  
file=${1:-/dev/stdin}                                                        
echo "Reading from $file"                                                    
nl "$file"                                                                   

$ cat myfile                                                                 
hello world                                                                  

$ ./myscript myfile                                                          
Reading from myfile                                                          
     1  hello world                                                          

$ ./myscript < myfile                                                        
Reading from /dev/stdin                                                      
     1  hello world                                                          

$ echo "something" | ./myscript                                              
Reading from /dev/stdin                                                      
     1  something         
Sign up to request clarification or add additional context in comments.

Comments

1

i would suggest to pass the filename as a an argument, you obviously know it anyway

echo "name $1"
while read line
do
    echo $line
done

and then:

./test.sh foo/bar.txt < foo/bar.txt

gives

name foo/bar.txt
1
2
3

if foo/bar.txt contains 1 2 3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.