[英]Bourne Shell doesn't find unix commands on script
#!/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)
PATH
是外壳程序用来存储目录列表的变量,在其中可以找到诸如cut
命令。 您重写了该变量的值,从而丢失了初始列表。 简单的解决方法是在for
循环中不要使用PATH
。 更为完整的答案是避免所有仅由大写字母组成的变量名,因为它们保留供外壳使用。 在您自己的所有变量名中至少包含一个小写字母或数字,以避免干扰Shell使用的当前(或将来)变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.