2014-09-23 109 views
0
#!/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 

運行它時我得到這個輸出(我跑使用相對路徑和完整路徑)Bourne Shell中沒有找到腳本UNIX命令

$ ./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)

+0

看起來你沒有'cut'。 – jwodder 2014-09-23 23:03:17

回答

3

PATH是shell用來存儲目錄列表的變量,其中可能會找到像cut這樣的命令。您重寫了該變量的值,失去了最初的列表。簡單的解決方法是在for循環中不使用PATH。更完整的答案是避免所有變量名僅由大寫字母組成,因爲這些變量名僅供shell使用。在所有自己的變量名稱中包含至少一個小寫字母或數字,以避免干擾shell使用的當前(或將來)變量。

+0

謝謝你完整的解釋,它完美地解決了。同樣謝謝你的建議,以避免聲明完整的大寫自變量 – FtheBuilder 2014-09-23 23:22:04