linux - bash:如何传递包含空格的参数

标签 linux bash shell arguments

我有两个 bash 脚本如下:

#main.sh
#!/bin/bash

files="file1 \"abc $1\" \"def $1\""

./upload.sh $files


#upload.sh
#!/bin/bash
for param in "$@"; do
    echo "${param}"
done

我正在尝试使用以下命令将包含空格的参数传递给 main.sh:

edeMacBook-Pro:doc Yves$ ./main.sh "Sri Lanka"

我认为 $files 会像这样:file1 "abc Sri Lanka""def Sri Lanka"。所以当我执行 ./upload.sh $files 时,应该将三个参数传递给 upload.sh

但是,当我执行命令时,我得到:

file1
"abc
Sri
Lanka"
"def
Sri
Lanka"

最佳答案

与其尝试构建一个“看起来像”包含所有参数的字符串(如果您真的想走那条路,然后可以尝试 eval ),不如尝试使用数组:

files=("file1" "abc $1" "def $1")
upload.sh "${files[@]}"

关于linux - bash:如何传递包含空格的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44215554/

相关文章:

linux - 有什么方法可以将子 linux 进程转移到另一个进程?

linux - Bash 19 个字符无缘无故消失

linux - 在 Bash/Awk/Perl 中有效地按列计算 token

bash - 如何使用脚本启动 ssh session 而不重定向 stdin?

python - 一个环境变量可供 python 子进程使用,而另一个则不可用

arrays - Bash 数组中的负下标

linux - 无法通过SSH进入运行Alpine Linux 3.10的Docker容器

linux - 显示套接字选项

python - 防止执行脚本时打开终端(crontab)

ruby - 从 Ruby 执行 PowerShell