1

如何消除命令行中的语法错误?我创建了一个这样的 bash 脚本:

#!/bin/bash

USER="$@"

sed 's/[!@#\$%^&*()]//g'> $@
done

if ! [ -f $@ -a -r $@ ] ; then
 echo "Wrong Option : "${USER}" is not readable or not exist" >&2
 exit -1
fi

cat "${@}"|while read -r line
do
IFS=, read -r f1 f2 f3 f4 f5 <<< "$line"
mysql --user=user --password=password --database=database <<EOF
INSERT INTO table_name VALUES($f1,'$f2','$f3','$f4',$f5);
EOF
done

我在其他终端上执行这个脚本,如下所示:

$ ./script.sh test!rr.txt
-bash: !rr.txt: event not found

实际上,这是一个将文本文件中的数据插入数据库表的脚本。如您所见,我想在插入文本文件之前检查文件是否存在。

我尝试使用 tr -d 命令和 sed 命令来消除命令行上的语法错误,但我认为它不起作用..

我的期望是:

$ ./script.sh test!rr.txt
Wrong Option : test!rr.txt is not readable or not exist

你有什么主意吗?谢谢。

4

4 回答 4

2

这是您需要调整期望的情况。Bash 只是在做你告诉它做的事情:在将参数传递给脚本之前执行历史扩展。关于引用论点或以其他方式转义“!”的其他答案 都是正确的,但他们假设您在将参数传递给您的脚本之前意识到历史扩展正在发生(您可以在其中检查文件是否存在)。

于 2012-05-01T16:29:23.340 回答
2

!在尝试评估该行之前,shell 将 解释为历史命令。尝试逃避它:

$ ./script.sh test\!rr.txt
于 2012-05-01T16:23:56.220 回答
2

如果要在文件名中包含 bash 特殊字符,请在文件名周围加上引号:

$ ./script.sh 'test!rr.txt'
于 2012-05-01T16:24:06.890 回答
1

将参数放在引号中以防止 shell 解释特殊符号:

$ ./script.sh "test!rr.txt"
于 2012-05-01T16:24:23.130 回答