#!/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”运行时,为什么代码不会进入“在这里输入”? 我觉得有两个参数的函数导致了问题,代码在一个参数
下工作正常答案 0 :(得分:2)
在尝试查找特定问题之前,您可能希望在代码中修复一些问题。相应地修改脚本后它可能会消失。如果问题仍然存在,我将用解决方案编辑我的答案。如果您决定应用以下更改,请在问题中更新您的代码。
[[
或[
的一致使用情况。 [[
是一个类似于[
命令(但功能更强大)的Bash关键字。
参见
除非您为POSIX sh撰写文章,否则我建议[[
。
将((
用于算术表达式。 ((...))
是一个算术命令,如果表达式非零,则返回退出状态0;如果表达式为零,则返回1。如果需要分配,还可以用作let
的同义词。请参阅Arithmetic Expression。
使用变量PWD
代替pwd
。 PWD
是包含当前工作目录的所有 POSIX shell中的内置变量。 pwd(1)
是一个 POSIX 实用程序,它将当前工作目录的名称输出到stdout。除非您正在编写某些非 - POSIX 系统,否则没有理由浪费时间执行pwd(1)
而不是仅使用PWD
。< / p>
function
关键字不可移植。我建议你不要使用它,只需写function_name() { your code here; } # Usage
$parent_dir
不是双引号。 “双引号”包含空格/元字符和每个展开的每个文字:"$var"
,"$(command "$var")"
,"${array[@]}"
,"a & b"
。见
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