gpt4 book ai didi

shell - 在 shell 中为实用程序构建参数的可移植方法?

转载 作者:行者123 更新时间:2023-12-04 03:57:42 26 4
gpt4 key购买 nike

我正在编写一个可以在一系列机器上运行的 shell 脚本。其中一些机器有 bash 2 或 bash 3。一些正在运行 BusyBox 1.18.4,其中 bin/bash存在但

  • /bin/bash --version根本不返回任何东西
  • foo=( "hello" "world" )提示接近意外的语法错误 "("括号内有和没有额外空格......所以数组似乎有限或丢失

  • 还有更现代或更全功能的 Linux 和 bash 版本。

    bash 脚本在运行时构建参数以调用某些实用程序(如 find)的最便携方式是什么? ?我可以建立一个字符串,但觉得数组会是一个更好的选择。除了上面的第二个要点...

    假设我的脚本是 foo你这样称呼它: foo -o 1 .jpg .png
    这是一些伪代码
    #!/bin/bash

    # handle option -o here
    shift $(expr $OPTIND - 1)

    # build up parameters for find here
    parameters=(my-diretory -type f -maxdepth 2)
    if [ -n "$1" ]; then
    parameters+=-iname '*$1' -print
    shift
    fi

    while [ $# -gt 0 ]; do
    parameters+=-o -iname '*$1' -print
    shift
    done

    find <new positional parameters here> | some-while-loop

    最佳答案

    如果您需要主要使用-POSIX sh,例如在busybox ash-named-bash 中可用,您可以直接使用 set 建立位置参数。

    $ set -- hello
    $ set -- "$@" world
    $ printf '%s\n' "$@"
    hello
    world

    一个更恰当的例子:
    $ set -- /etc -name '*b*'
    $ set -- "$@" -type l -exec readlink {} +
    $ find "$@"
    /proc/mounts

    关于shell - 在 shell 中为实用程序构建参数的可移植方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30493978/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com