shell bash脚本中的函数:command not found

ddrv8njm  于 12个月前  发布在  Shell
关注(0)|答案(1)|浏览(146)

我正在学习bash,我正在尝试调用这个函数,它将文件从另一个目录复制到另一个目录,其中文件按字母顺序颠倒。每当我尝试运行脚本时,它会说“找不到排序器”。我应该把函数赋值给一个变量吗?
我得到“未找到命令”。当我使用函数中的代码调用或创建函数时,它会完美地运行。

#!/bin/bash
sourcedir=$1
targetdir=$2

if [[ $# != 2 ]]
then
  echo -e "Error: Expected two input parameters.\nUsage: ./sortedcopy.sh <sourcedirectory> <targetdirectory>"
exit 1



elif [[ ! -d $1 ]]
then
  echo -e "Error: Input parameter #1 '$1' is not a directory.\nUsage: ./sortedcopy.sh <sourcedirectory> <targetdirectory>"
 exit 2

function thesorter() 
{
          mkdir $2
        cd $2
        path2=$(pwd)
        cd $(cd -)
        cd $1
        i=1
        for file in $(ls -r )
        do
                cp $file $path2/$((i++)).$file
        done
}

elif [[ ! -d $2 ]]
then
        thesorter $sourcedir $targetdir

else
 echo "Directory '$2' already exists. Overwrite? (y/n)"
 read answer
 if [[ $answer = y ]]
 then
       rm -r $2
       thesorter $sourcedir $targetdir
 fi
   exit 3
fi
kxxlusnw

kxxlusnw1#

您遇到的错误消息“thesorter not found”很可能是由于thesorter函数的位置。Bash函数应该在调用之前定义。
在您的脚本中,您已经在elif块中定义了thesorter函数,这意味着只有在满足elif块中的条件时才会定义该函数。如果导致elif块的条件都不满足,则函数将不会被定义,并且当您尝试调用它时,您将获得“command not found”错误。
要解决此问题,您应该在条件语句之前定义thesorter函数。下面是修改后的脚本:

#!/bin/bash

# Define the thesorter function before conditional statements
function thesorter() {
    mkdir "$2"
    cd "$2" || exit 1
    path2=$(pwd)
    cd - || exit 1
    cd "$1" || exit 2
    i=1
    for file in $(ls -r)
    do
        cp "$file" "$path2/$((i++)).$file"
    done
}

sourcedir="$1"
targetdir="$2"

if [[ $# != 2 ]]
then
    echo -e "Error: Expected two input parameters.\nUsage: ./sortedcopy.sh <sourcedirectory> <targetdirectory>"
    exit 1
elif [[ ! -d $1 ]]
then
    echo -e "Error: Input parameter #1 '$1' is not a directory.\nUsage: ./sortedcopy.sh <sourcedirectory> <targetdirectory>"
    exit 2
elif [[ ! -d $2 ]]
then
    thesorter "$sourcedir" "$targetdir"
else
    echo "Directory '$2' already exists. Overwrite? (y/n)"
    read -r answer
    if [[ $answer = y ]]
    then
        rm -r "$2"
        thesorter "$sourcedir" "$targetdir"
    fi
    exit 3
fi

在这个修改后的脚本中,thesorter函数是在开始时定义的,以确保它在整个脚本中都可用。此外,我还做了一些小的改进,通过将目录路径用双引号括起来,来正确处理带有空格的目录路径。

相关问题