使用功能时,如果条件不进入 [英] not entering if condition when using a function

查看:87
本文介绍了使用功能时,如果条件不进入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#!/bin/bash

function func_name {

arg1=$1; arg2=$2; 

if [[ "${arg1}" == "abcd" ]]; then
    echo enterd abcd condition
else
    echo entered else
fi

}

export -f func_name

find . -name "*" -type d -exec bash -c '( cd {} &&

func_name;

)' bash $1 $2 {} \;

试图运行具有if条件作为一个子shell里发现语句的功能。它只是进入别人的一部分。为什么?

Trying to run a function having if condition as a subshell inside find statement. It just enters else part. Why?

推荐答案

目前还不清楚哪些参数应传递的地方,但你目前的尝试肯定是错误的。你是不是合格的任何的参数 FUNC_NAME 当你调用它,所以$ ARG1正在扩大为空字符串。我怀疑你想要的东西像

It's not clear what arguments should be passed where, but your current attempt is certainly wrong. You aren't passing any arguments to func_name when you are calling it, so "$arg1" is expanding to the empty string. I suspect you want something like

find . -name "*" -type d -exec bash -c 'cd "$1" && func_name "$2" "$3"' {} "$1" "$2" \;

在这里, FUNC_NAME 明确给出传递给原始脚本的参数。你不需要在参数子外壳 -c ,因为整个命令在一个单独的进程已经运行。

Here, func_name is explicitly given the arguments passed to the original script. You don't need the subshell in the argument to -c, since the entire command is already run in a separate process.

如果您使用的是庆典 4或更高版本,你可能并不真正需要使用找到

If you are using bash 4 or later, you probably don't actually need to use find.

shopt -s globstar
for d in **/*/; do
    pushd "$d"
    func_name "$1" "$2"
    pops
done

这篇关于使用功能时,如果条件不进入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆