回答
One should never parse the output of ls。如果您正在使用bash,請嘗試此操作
if [ -d "$DIRECTORY" ]; then
# will enter here if $DIRECTORY exists.
fi
test -d 'name' && echo "It is there"
的test -d 'name'
可用於if語句之類爲好。
試試這個嗎?
ls -l | grep ^d name
這將在名爲'name'的文件的一行的開頭處搜索'd'。 – Kevin 2013-05-03 14:44:07
我當然不是專家。但它對我有用嗎?如果你有第二個,我不介意吸取教訓。這個:ls -l | grep^d Web 返回這個:grep:Web:當我嘗試使用時,它是我的一個目錄 – eatonphil 2013-05-03 14:46:04
這種方法沒有什麼*錯誤*,除非你不應該從ls解析輸出[see link](http:/ /mywiki.wooledge.org/ParsingLs)'ls -l'顯示使用長列表的結果,其中第一個字段是文件模式位。如果它作爲文件夾,第一個字符將是一個'd',與正則表達式'^ d'相匹配。所以,這種方法有效,但它有缺陷(再次請參閱鏈接)。 – 2013-05-03 15:01:39
這就是-d
測試的目的。簡單地說:
if [ -d "name" ]; then
echo "yay!"
else
echo "nay!"
fi
再次出現同樣的錯誤。 '〜> if [[-d「a」]];然後cd a;否則回顯「ER」; fi' '-bash:[[-d:command not found' 'ER' – 2013-05-03 15:21:21
[]中的空格很重要。即'[-d「a」]'會起作用,但'[-d「a」]'不會。另外,'test -d「a」'將在bash和csh中工作 – 2013-05-03 16:04:31