这是我的问题。我有脚本,我想确保调用脚本时输入的参数与脚本中的变量名匹配。
例如:
./ valid foo< - 是脚本调用
#!/bin/bash
PARAM=$1
VAR=/foo/
if grep -c $PARAM == $VAR
then
echo yes
fi
echo no
我使用grep的时间最差,我不确定如何在脚本中正确使用它,在浏览互联网后我觉得我需要一些关于我的问题的具体反馈。
谢谢,
EA
答案 0 :(得分:3)
这不健全,但你可以这样做:
if echo "$VAR" | grep -q "$PARAM"; then
最好简单地做:
if test "$VAR" = "$PARAM"; then
如果你想匹配一个正则表达式,bash允许:
if [[ "$VAR" =~ "$PARAM" ]]; then
将固定字符串$VAR
与正则表达式$PARAM
匹配。如果$VAR
是正则表达式,则应该颠倒参数的顺序。 (即[[ "$PARAM" =~ "$VAR ]]
。)
答案 1 :(得分:0)
您可以在脚本中搜索,因为声明后面是等号的名称:
if egrep "^\s*$PARAM=" $0 then echo yes else echo no fi
答案 2 :(得分:0)
列出变量使用
set -o posix ; set
posix thingie阻止函数列表。
为了隔离脚本本地的参数,从shell运行并存储结果, 然后从脚本运行它并比较输出
(set -o posix ; set) >/tmp/variables.before
(set -o posix ; set) >/tmp/variables.after