如果在find语句中使用命令行参数调用函数时,函数内的条件不能正常工作

时间:2016-04-14 09:55:56

标签: bash shell

#!/bin/bash

# Code to generate script usage
if [[ "$#" -ne 1 ]] && [[ "$#" -ne 2 ]]; then
    flag=1;
elif ! [[ "$1" == "abcd" || "$1" == "dcba" ]]; then 
    echo "Invalid"
    flag=1;
fi

while [ $# -gt 1 ]
do
    case $2 in
        'streams')
            ;;
        *)
            echo "unrecognised optional arg $2"; flag=1;
            ;;
    esac
    shift
done

if [ "$flag" == "1" ]; then
    echo "Usage:"
    exit
fi

function main {

arg1=$1
streams=$2
    if [ "${streams}" == "streams" ]; then
        echo entering here
    else
       echo entering there
    fi
}

parent_dir=`pwd`
find $parent_dir -name "*" -type d | while read d; do
    cd $denter code here
    main $1 $2
done

当脚本使用参数“abcd”和“streams”运行时,为什么代码不会进入“在这里输入”? 我觉得有两个参数的函数导致了问题,代码在一个参数

下工作正常

2 个答案:

答案 0 :(得分:2)

在尝试查找特定问题之前,您可能希望在代码中修复一些问题。相应地修改脚本后它可能会消失。如果问题仍然存在,我将用解决方案编辑我的答案。如果您决定应用以下更改,请在问题中更新您的代码。

  1. [[[的一致使用情况。 [[是一个类似于[命令(但功能更强大)的Bash关键字。 参见

    除非您为POSIX sh撰写文章,否则我建议[[

  2. ((用于算术表达式。 ((...))是一个算术命令,如果表达式非零,则返回退出状态0;如果表达式为零,则返回1。如果需要分配,还可以用作let的同义词。请参阅Arithmetic Expression

  3. 使用变量PWD代替pwdPWD是包含当前工作目录的所有 POSIX shell中的内置变量。 pwd(1)是一个 POSIX 实用程序,它将当前工作目录的名称输出到stdout。除非您正在编写某些 - POSIX 系统,否则没有理由浪费时间执行pwd(1)而不是仅使用PWD。< / p>

  4. function关键字不可移植。我建议你不要使用它,只需写function_name() { your code here; } # Usage

  5. $parent_dir不是双引号。 “双引号”包含空格/元字符和每个展开的每个文字:"$var""$(command "$var")""${array[@]}""a & b"。见

  6. ShellCheck您的代码在上传之前。

答案 1 :(得分:0)

Replace the while condition logic with an if condition, so that shift is no longer required. Shift was the devil I was facing I found.

#!/bin/bash

# Code to generate script usage
if [[ "$#" -ne 1 ]] && [[ "$#" -ne 2 ]]; then
    flag=1;
elif ! [[ "$1" == "abcd" || "$1" == "dcba" ]]; then 
    echo "Invalid"
    flag=1;
fi
#while [[ $# -gt 1 ]]
#do
#    case $2 in
#       'streams')
#           ;;
#        *)
#            echo "unrecognised optional arg $2"; flag=1;
#            ;;
#    esac
#    shift
#done

if [[ $2 == "streams" ]]; then
   :
elif [[ (-z $2) ]]; then
    : 
else
    echo "unrecognised optional arg $2"; flag=1;
fi


if [[ "$flag" == "1" ]]; then
    echo "Usage:"
    exit
fi

function main {

streams=$2

    if [[ "${streams}" == "streams" ]]; then
        echo entering here
    else
       echo entering there
    fi
}

parent_dir=`pwd`
find $parent_dir -name "*" -type d | while read d; do
    cd $d
    main $1 $2
done