【问题标题】:Second parameter is getting the content of the first parameter in shell script function [duplicate]第二个参数是获取shell脚本函数中第一个参数的内容[重复]
【发布时间】:2020-10-23 12:42:15
【问题描述】:

我在 shell 脚本中创建一个函数,我需要传递 2 个参数。一个是路径,另一个是数组。但问题是第二个参数获取的是第一个参数的内容。

例如:

input_files_path="./path"
array=("Word1" "Word2" "Word3")

list_files(){
  path=$1
  array_in=("${@}")

  echo "${array_in[@]}"

}

list_files "${input_files_path}" "${array[@]}"

输出:

./path Word1 Word2 Word3

如果我将第二个参数更改为

array_in=$2

它不起作用。

【问题讨论】:

  • 这可能会有所帮助:help shift

标签: bash shell parameters


【解决方案1】:

当您调用带参数的函数时,将一个参数分配给变量这一事实不会将其从参数列表中删除。

您需要做的是将第一个参数分配给一个变量,然后使用shift 从参数列表中删除该参数。那么当你使用@时,就不再包含第一个参数了。

像这样:

#!/bin/bash

input_files_path="./path"
array=("Word1" "Word2" "Word3")

list_files(){
  path=$1
  # remove the $1 argument from $@
  shift
  array_in=("${@}")

  echo "${array_in[@]}"

}

list_files "${input_files_path}" "${array[@]}"

【讨论】:

    猜你喜欢
    • 2012-06-18
    • 1970-01-01
    • 2018-05-02
    • 2017-12-12
    • 2011-04-29
    • 2011-09-14
    • 2021-12-20
    • 2019-07-15
    • 2013-11-09
    相关资源
    最近更新 更多