How to implement shell input redirection

How to write a shell that collects contents from a file and enters a command? it would look like this: $ command <input file I don’t know how to start.

+4
source share
4 answers

Using wc as an example:

 $ wc < input_file > output_file 

Explanation

  • wc : this is the command (or inline shell) that you invoke
  • < input_file : read input input_file
  • > output_file': write output into output_file`

Note that many commands will accept the input file name as one of its cmdline arguments (without using < ), for example:

  • grep pattern file_name
  • awk '{print}' file_name
  • sed 's/hi/bye/g filename`
+1
source

You need to specify the descriptor of the input file of your shell program in the input file. In c, this is achieved by calling int dup2(int oldfd, int newfd); whose task is newfd to be a copy of oldfd, closing newfd if necessary.
On Unix / Linux, each process has its own file descriptors, which are stored as follows:

0 - Standard input (stdin) 1 - Standard output (standard output) 2 - Standard error (stderr)

So, you must point the stdin handle to the input file you want to use. Here is how I wrote a few months before:

 void ioredirection(int type,char *addr) { // output append redirection using ">>" if (type == 2) { re_file = open(addr, O_APPEND | O_RDWR, S_IREAD | S_IWRITE); type--; } // output redirection using ">" else if (type==1) re_file = open(addr, O_TRUNC | O_RDWR, S_IREAD | S_IWRITE); // input redirection using "<" or "<<" else re_file = open(addr, O_CREAT | O_RDWR, S_IREAD | S_IWRITE); old_stdio = dup(type); dup2(re_file, type); close(re_file); } 
0
source

Using the read command:

you can read using bash script input

inputreader.sh

 #!/bin/bash while read line; do echo "$line" done 

Output

 $ echo "Test" | bash ./inputreader.sh Test $ echo "Line 1" >> ./file; echo "Line 2" >> ./file $ cat ./file | bash ./inputreader.sh Line 1 Line 2 $ bash ./inputreader.sh < ./file Line 1 Line 2 
0
source

you can use xargs for this:

for example, you have a file that has a list of file names.

 cat your_file|xargs wc -l 

wc -l - your cat and xargs command will pass each line in the file as input to wc -l

therefore, the output will consist of counting the lines of all files whose names are present in the input file, the main thing here is xargs will pass each line as an input to wc -l

0
source

Source: https://habr.com/ru/post/1446365/


All Articles