我在Bash中遇到了如何使用\t
之类的特殊字符传递参数的问题。
我知道以下内容以保留引号:
function my_grep {
cmd="grep '$@'"
eval $cmd;
}
这样我就可以my_grep "hello world"
。
但似乎我不能以这种方式保存,例如
my_grep "hello\tworld"
关于如何使这项工作的任何想法?
答案 0 :(得分:7)
解决方案很简单:不要将命令存储在变量中!见BashFAQ #50: I'm trying to put a command in a variable, but the complex cases always fail!。另外,请勿使用eval
;它会导致各种奇怪的问题。如果你跳过这些(并正确使用"$@"
),问题就会消失:
my_grep() {
grep "$@"
}
请注意,如果您使用my_grep "hello\tworld"
调用它,它实际上并不传递制表符,它会传递反斜杠后跟字母“t” - grep
的某些实现会解释作为匹配选项卡。如果您的grep
版本没有这样做,您可以使用my_grep $'hello\tworld'
传递实际标签。
答案 1 :(得分:-4)
您可以在-F
中使用grep
选项作为文字字符串。测试脚本:
#!/bin/bash
function my_grep {
cmd="grep -F '$@' hello.txt"
eval $cmd
}
my_grep "hello world\t"
输入文件:
$ cat hello.txt
hello world\t
hello world
输出结果为:
$ sh grep_test.sh
hello world\t
另外,我会更改function
行(个人而言,我宁愿避免eval
):
result=`grep -F "${@}" hello.txt`
echo $result
希望这会有所帮助。