linux - 解析 bash 脚本的输入参数时带空格的参数

标签 linux bash shell terminal ubuntu-16.04

我写了一个 bash 脚本,它按名称获取参数并读取键值对中的值。下面是我如何运行脚本的示例。

 sh test.sh param1='a' param2='b'

然后我在我的脚本中引用 $param1 和 $param2 等输入参数。下面是我为此编写的脚本。

for item in $@; do
case $item in
(*=*) eval $item;;
esac
done

但是当参数的值中有空格时,它只取空格之前的部分。

 param3='select * from'

只会将“select”分配给 param3 而不是整个字符串。我怎样才能做到这一点?任何帮助将不胜感激。

编辑:

Inian 的回答之后

for item in $@; do
case "$item" in
(*=*) eval "$item";;
esac
done

最佳答案

您可以通过引用 "$@" 并使用 declare 而不是 eval 来做到这一点:

for item in "$@"; do
case $item in
(*=*) declare "$item" ;;
esac
done

但是,现在这是一个 bash 脚本,因此您必须使用 bash test.sh 而不是 sh test.sh

来运行它

关于linux - 解析 bash 脚本的输入参数时带空格的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41560611/

相关文章:

linux - Netcat HTTP 发布

java - 在linux中使用java web服务进行IPC(进程间通信)

linux - 如何使用 bash 脚本从文本文件中选择特定范围的行

linux - Shellscript - 按 block 读取

c++ - 使用 Eclipse 调试外部控制台程序

c++ - 如何同时使用 2 个套接字 PF_INET 和 PF_PACKET?

linux - log4cplus RollingFileAppender 不创建新文件

Bash:查找具有最大行数的文件

linux - 执行命令(从变量)然后显示正确的 pid?

shell - 如何打开hdfs ://localhost:54310/user/hduser/