当用户运行:
./script_name <input_file
...这是相当于正是,如果他们做了以下内容:从input_file
(exec <input_file; exec ./script_name)
...第一重定向标准输入,然后调用脚本名为./script_name
没有任何参数。
您可以使用操作系统特定的接口来获取与句柄关联的文件名(如果有的话),但使用其中一种会使您的脚本只能在操作系统上运行,接口;这不值得。
# very, very linux-specific, won't work for "cat foo | ./yourscript", generally evil
if filename=$(readlink /proc/self/fd/0) && [[ -e $filename ]]; then
set -- "[email protected]" "$filename" # append filename to the end of the argument list
fi
如果你想在给出的参数,以避免提示输入,并有这样的说法的文件名,然后不采取它在标准输入,但作为一个参数,并做脚本内重定向自己:
#!/bin/bash
if [[ $1 ]]; then
exec <"$1" # this redirects your stdin to come from the file
fi
# ...put other logic here...
...并让用户调用你的脚本:
./script_name input_file
正如./yourscript <filename
运行yourscript
与filename
它的标准输入的内容,脚本用./yourscript filename
它调用exec <"$1"
执行该命令后,将具有filename
它的标准输入的内容调用。
'./script_name input_file',然后'echo $ 1'。 – bishop
我必须从我的输入文件中读取所有行。它具有所有的用户输入。如果我不使用该操作员,它会提示用户输入。 – Rock26
显示你的脚本,或等效的例子,所以我们可以看到它从标准输入 – chepner