bash - 如何将字符串作为 bash 脚本的命令行参数传递?

标签 bash

<分区>

我想将一个字符串作为命令行参数传递给 bash 脚本; 简单地说,我的 bash 脚本是:

>cat test_script.sh

for i in $*
do 
echo $i
done

我输入了

bash test_script.sh test1 test2 "test3 test4"

输出:

test1
test2
test3
test4

我期望的输出:

test1
test2
test3 test4

我尝试使用反斜杠 (test1 test2 "test3\test4") 和单引号,但没有得到预期的结果。

如何获得预期的输出?

最佳答案

你需要使用:

for i in "$@"
do echo $i
done

甚至:

for i in "$@"
do echo "$i"
done

第一个会在一个参数中丢失多个空格(但会将一个参数的单词放在一起)。第二个保留参数中的空格。

你也可以省略in "$@"子句;如果你写 for i 是隐含的(但就我个人而言,我从不使用速记)。

关于bash - 如何将字符串作为 bash 脚本的命令行参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13175727/

相关文章:

php - 用于运行 php 脚本的 Bash 脚本

linux - 如何为我的linux系统下的每个人设置环境变量?

python - Bash/Python 比较 2 个 CSV 文件输出到 .htaccess 重定向

linux - 将 Mac 地址保存在 bash 脚本中的变量中并使用它来检查更改

bash - 删除<某些命令> | netcat 通过 ssh 到后台

linux - 在 Linux/bash 下拆分文件及其行

linux - 如何在 bash 中使用 'while ..; do..; done'

linux - 如何向awk添加 echo ?

javascript - 终端:% Node example.js -bash:fg:没有这样的工作

regex - 使用正则表达式通过 Bash 检查范围