Bash 如果在find语句中使用命令行参数调用函数时,函数内的条件未按预期工作
当脚本使用参数“abcd”和“streams”运行时,为什么代码不输入“entering here”?Bash 如果在find语句中使用命令行参数调用函数时,函数内的条件未按预期工作,bash,shell,Bash,Shell,当脚本使用参数“abcd”和“streams”运行时,为什么代码不输入“entering here”? 我觉得有两个参数的函数是导致问题的原因,在试图找到具体问题之前,代码使用一个参数运行良好。在相应地修改脚本后,它可能会消失。如果问题仍然存在,我将用解决方案编辑我的答案。如果您决定应用以下更改,请更新问题中的代码 一致使用[[或[[[是一个Bash关键字,与[命令类似(但功能更强大)。 看 除非您是为POSIX sh编写的,否则我建议您使用[ 对算术表达式使用(。(…)是一个算术命令,
我觉得有两个参数的函数是导致问题的原因,在试图找到具体问题之前,代码使用一个参数运行良好。在相应地修改脚本后,它可能会消失。如果问题仍然存在,我将用解决方案编辑我的答案。如果您决定应用以下更改,请更新问题中的代码
[[
或[
[[
是一个Bash关键字,与[
命令类似(但功能更强大)。
看
[
(
。(…)
是一个算术命令,如果表达式为非零,则返回退出状态0;如果表达式为零,则返回退出状态1。如果需要赋值,则还可用作let
的同义词。请参阅PWD
代替PWD
PWD
是包含当前工作目录的所有POSIX外壳中的内置变量。PWD(1)
是一个POSIX实用程序,它将当前工作目录的名称打印到stdout。除非您是为一些非-POSIX系统编写的,否则没有理由浪费时间执行pwd(1)
,而不仅仅是使用pwd
function
关键字不可移植。我建议您避免使用它,只需编写function\u name(){your code here;}#用法
$parent\u dir
不是双引号。“双引号”每个包含空格/元字符和每个扩展的文本:“$var”
,“$(命令“$var”)”
,“${array[@]}”
,“a&b”
。请参阅
尝试使用
-x
运行,查看[“${streams}”==“streams”]
扩展。通过这些语句,您在这里做的是什么?cd$denter code here main$1$2
您的代码产生了一个您没有提到的错误。$/test\u script.bash about streams./test\u script.bash:line 41:cd:code:没有这样的文件或目录
@Inian我很确定这是SO编辑器的人工制品。@Inian that lin这是一个很好的答案。请注意引号在命令替换中的作用:“$(command“$var”)”
是有效的引号,可以这样分解:命令“$var”
和“$(…)”
关于第4点:[
和((
也不可移植,但它们提供了实实在在的好处,以换取牺牲可移植性。我能想到的使用函数的唯一原因是定义一个与预先存在的别名同名的函数(除了几乎不必这样做外,与POSIX兼容的代码仍然可以这样做。)我很确定关键字的存在只是为了从ksh
移植代码(在bash
中,使用关键字和不使用关键字定义的函数之间没有区别。)@chepner感谢您的评论。但我不知道这是否是解决此问题的正确方法
#!/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
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