首页 > 解决方案 > 如何将字符串数组传递给 Bash 脚本并加入该数组?

问题描述

我想在 string 上加入一个字符串数组"%2C+"。我的 shell 脚本launch看起来像这样。

#!/bin/bash

function join_by { local d=$1; shift; echo -n "$1"; shift; printf "%s" "${@/#/$d}"; }

selectQuery=$(join_by "%2C+" $1)
echo selectQuery

但是当我运行时./download-data $("state_code" "county_code"),我在终端中收到此错误:bash: state_code: command not found.

我需要将参数作为数组传递,因为我计划稍后传递更多数组。类似的东西./download-data $("state_code" "county_code") $("more" "string")

标签: bashshell

解决方案


让您的脚本在单独的参数中接受多个字符串:

#!/bin/bash

function join_by { local d=$1; shift; echo -n "$1"; shift; printf "%s" "${@/#/$d}"; }

selectQuery=$(join_by "%2C+" "$@")
echo "$selectQuery"

然后使用多个参数运行它:

./download-data "state_code" "county_code"

推荐阅读