【问题标题】:can't access command-line arguments from inside a function无法从函数内部访问命令行参数
【发布时间】:2017-05-24 07:27:00
【问题描述】:

即使我的退出状态为 0,我的脚本似乎也无法运行

它一直有效,直到我用

makedrivetree ()
{
}

语法。

如果删除它并保留whiledone 之间的所有内容,它可以正常工作。

我已将它作为 makedrivetree 保存在我的 ~/bin 文件夹中

这是完整的功能:

#!/usr/bin/env bash

# a script to write the contents of a directory in tree form and save it to a .txt file

### CONSTANTS

DATE="$(date +%Y%m%d)"

### FUNCTIONS

makedrivetree ()

{
    while [ "${*}" != "" ] ; do

        #set $DRIVE as the first arugment sent to script
        DRIVE="${1}"
        #set $OUTPUT
        OUTPUT="/Users/$USER/Desktop/$(basename "${DRIVE}")_contents_"${DATE}".txt"
        #run tree
        tree -I "*.dpx" --si --du -U -o "${OUTPUT}" "${DRIVE}"

        #check $? for errors
        if [ "$?" -eq "0" ] ; then
            echo 'done. moving to next drive.'
        else
            echo 'error'
        fi

        shift

    done
}

#call the function(s)

makedrivetree

echo 'makedrivetree exited with status' $?

exit

【问题讨论】:

  • 你没有将参数传递给你的函数,这可能是问题所在。
  • 嗨@Aaron你能详细说明或建议修复吗?谢谢!
  • 哦,我明白了。当我调用该函数时,我必须执行makedrivetree $@ 之类的操作。
  • 是的,就是这样!
  • 仅供参考 -- 而不是 tree ...; if [ "$?" -eq "0" ]; then ...,请考虑 if tree ...; then -- 更短,更不容易出错(所以像额外的日志记录这样的东西不会破坏$?)。

标签: bash function


【解决方案1】:

makedrivetree "$@" 调用函数解决了这个问题。

(在 cmets 中也有出色的提示/解释/答案)

【讨论】:

  • 这实际上是错误的。改用makedrivetree "$@" -- 不带引号的$@,然后./yourprogram "first argument" "second argument" 以与./yourprogram "first" "argument" "second" "argument" 相同的方式传递。
  • 谢谢! @CharlesDuffy
【解决方案2】:

您没有向该函数传递任何参数。查看函数中的第一行代码

while [ "${*}" != "" ]  

您所做的是测试是否有任何参数传递给函数。当您调用该函数 (makederivetree) 时,您没有向它传递任何参数。总结一切,当你调用你的函数时,while循环永远不会运行,因为你指定的条件。

【讨论】:

  • 酷。谢谢! @0.sh.
  • 是否有优先于通过$@$1 传递参数的偏好?
  • 另外,如果函数从未真正运行过,为什么它仍然以 0 退出?
  • @Bleakley - 函数运行。它只是没有执行 while 循环内的块,因为它从未收到任何参数。
  • @0.sh - bash 没有做出任何假设。 Bash 执行了函数,但是 while 循环中的条件为假,所以它转到下一行,即函数的结尾。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-30
  • 2015-01-17
  • 2011-02-14
  • 2020-09-30
  • 2010-09-30
  • 2013-11-30
相关资源
最近更新 更多