如何将字符串读入一行(未知长度)

时间:2015-11-09 21:10:59

标签: bash unix input

如何在bash中将一个未知长度的行作为字符串从变量中获取?

我想用$ 1 $ 2 $ 3调用函数,依此类推,但每次长度,或者换句话说参数的数量都可以改变。

我试图做"阅读-e"和其他一些选择,我很乐意为这个简单的任务获得一些帮助。

function find_sus {

while read -a domain; do #here I try to write the parameters into an array
p=0
while((p<$2)); do #Here just fo a check, I try to print all the array's elements
echo ${domain[p]};
let p++;
done 

read -e domains #Here I want to read into domains a string 
find_sus $domains $# #here I want to give the string and the amount of parameters to the function 

一般来说,我有功能,我想在这里给出一个未知数量的参数,一次一个,然后在每个参数的函数中用已编写的脚本进行操作。

好的,为了更多清关,我的功能是find_suspect。 我告诉你我的问题。我所知道的是如何给函数有限而不是大量的参数,比如find_suspect $ 1 $ 2 $ 3等等。

任何人都可以给我一个如何给出函数n参数的例子,而不是把它们都写成$ 1 ... $ n。 我尝试用循环来做     当我

但当然这不是正确的做法。

2 个答案:

答案 0 :(得分:1)

您可以使用shift:

循环遍历未知的参数nr
clear

function findsus {
   while [ $# -gt 0 ]; do
      echo Param $1
      shift
   done
}

findsus one two three
findsus 1 2 3 4 5 6 7 8 9
findsus "Argument in quotes"

答案 1 :(得分:0)

据我了解,您希望提供单个字符串作为readsus的参数,然后让readsus将其分成单个单词并每行打印一个单词。如果是这种情况,请像这样定义readsus

$ findsus() { for d in $*; do echo "$d"; done; }

$*提供所有参数。由于它没有引用,因此shell会将其分解为单词。

例如:

$ findsus "abc.com def.com a.net"
abc.com
def.com
a.net

改进:避免路径名扩展

在上面,shell执行单词拆分(我们想要的)和路径名扩展(我们可能不会)。通过额外的步骤,我们可以将输入字符串拆分为数组,而无需 shell执行路径名扩展:

$ findsus() { read -r -a domains <<<"$*"; for d in "${domains[@]}"; do echo "$d"; done; }
$ findsus "abc.com * def.com"
abc.com
*
def.com