簡體   English   中英

Linux Bash Shell腳本:如何“ls”目錄並檢查一些輸出字符串?

[英]Linux Bash Shell Script: How to “ls” a directory and check some output string?

我只是Linux Shell Scripting的新手。 我需要知道的是,通常在命令行中,我們只需使用:

# ls /var/log
audit            ConsoleKit     cups        maillog           messages           ntpstats  secure-20130616   spooler-20130623  vsftpd.log-20130616
boot.log         cron           dmesg       maillog-20130616  messages-20130616  prelink   secure-20130623   spooler-20130701  vsftpd.log-20130623
... . . . ..

然后

# ls /var/aaaaaaaaaaaaaaa
ls: cannot access /var/aaaaaaaaaaaaaaa: No such file or directory

所以使用Shell腳本:

  • 我該如何運行命令: # ls /var/aaaaaaaaa
  • 然后檢測是否有輸出字符串ls: cannot access

注意 :您可能會問我是否只想檢測故障。 或輸出字符串。 我非常渴望知道這兩種方式。 謝謝。

要檢查目錄:

if [ ! -d '/var/aaaaaaa' ]; then
   echo 'no dir!'
fi

對於文件:

if [ ! -f '/var/aaaaaaa' ]; then
   echo 'no file!'
fi

檢查輸出:

if ls '/var/aaaaaaa' 2>&1 | grep 'No such'; then  
   echo 'no such'; 
fi

要檢查ls何時失敗:

if ! ls '/var/aaaaaaa' &> /dev/null; then 
  echo 'failed'
fi

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM