【问题标题】:Linux Bash Shell Script: How to "ls" a directory and check some output string?Linux Bash Shell 脚本:如何“ls”一个目录并检查一些输出字符串?
【发布时间】:2013-07-11 04:28:08
【问题描述】:

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

# 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

注意:您可能会问我是否只想检测失败。或输出字符串。我很想知道这两种方式。谢谢。

【问题讨论】:

  • 你真的想检查那个输出字符串,还是仅仅检测失败?
  • 其实你可能会说FAILURE,来检查目录是否存在。但我也很想知道如何检查输出字符串。

标签: linux bash shell grep


【解决方案1】:

检查目录:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    • 1970-01-01
    • 2014-09-17
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    相关资源
    最近更新 更多