简体   繁体   中英

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

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

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         

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM