Bourne Shell在脚本上找不到unix命令

时间:2014-09-23 22:59:03

标签: shell unix freebsd

#!/bin/sh

echo "Insert the directory you want to detail"
read DIR
#Get the files:
FILES=`ls "$DIR" | sort`
echo "Files in the list:"
echo "$FILES"
echo ""
echo "Separating directories from files..."
for FILE in $FILES
do
    PATH=${DIR}"/$FILE"
    OUTPUT="Path: $PATH"
    if [ -f "$PATH" ]; then
        NAME=`echo "$FILE" | cut -d'.' -f1`
        OUTPUT=${OUTPUT}" (filename: $NAME"
        EXTENSION=`echo "$FILE" | cut -s -d'.' -f2`
        if [ ${#EXTENSION} -gt 0 ]; then
            OUTPUT=${OUTPUT}" - type: $EXTENSION)"
        else
            OUTPUT=${OUTPUT}")"
        fi
    elif [ -d "$PATH" ]; then
        OUTPUT=${OUTPUT}" (dir name: $FILE)"
    fi
    echo "$OUTPUT"
done

我在运行时获得此输出(我使用相对路径和完整路径运行)

$ ./problem.sh
Insert the directory you want to detail
.
Files in the list:
directoryExample
problem.sh

Separating directories from files...
Path: ./directoryExample (dir name: directoryExample)
./problem.sh: cut: not found
./problem.sh: cut: not found
Path: ./problem.sh (filename: )
$ 
$ 
$ ./problem.sh
Insert the directory you want to detail
/home/geppetto/problem
Files in the list:
directoryExample
problem.sh

Separating directories from files...
Path: /home/geppetto/problem/directoryExample (dir name: directoryExample)
./problem.sh: cut: not found
./problem.sh: cut: not found
Path: /home/geppetto/problem/problem.sh (filename: )
$

正如您所见,我收到了" cut: not found"排列文件类型的输出字符串时两次。为什么? (我使用Free BSD)

1 个答案:

答案 0 :(得分:3)

PATH是shell用于存储可能找到cut等命令的目录列表的变量。你覆盖了该变量的值,丢失了初始列表。简单的解决方法是在PATH循环中不使用for。更完整的答案是避免所有变量名称仅由大写字母组成,因为它们保留供shell使用。在所有自己的变量名中包含至少一个小写字母或数字,以避免干扰shell使用的当前(或将来)变量。