检查文件类型后检查执行命令

时间:2011-06-26 11:34:21

标签: bash file lpr

我正在处理一个bash脚本,它根据文件类型执行命令。我想使用“文件”选项而不是文件扩展名来确定类型,但我对这个脚本的东西很蠢,所以如果有人可以帮助我,我会非常感激! - 谢谢!

这里我想要包含该功能的脚本:

 #!/bin/bash

 export PrintQueue="/root/xxx";

 IFS=$'\n'

 for PrintFile in $(/bin/ls -1 ${PrintQueue}) do

     lpr -r ${PrintQueue}/${PrintFile};

 done

关键是,所有PDF文件都应使用lpr命令打印,所有其他文件应使用ooffice -p打印

3 个答案:

答案 0 :(得分:1)

你正在经历许多额外的工作。这是惯用的代码,我将让手册页提供对这些部分的解释:

#!/bin/sh

for path in /root/xxx/* ; do
    case `file --brief $path` in
      PDF*) cmd="lpr -r" ;;
      *) cmd="ooffice -p" ;;
    esac
    eval $cmd \"$path\"
done

一些值得注意的要点:

  • 使用sh而不是bash增加了可移植性并缩小了如何做事的选择
  • 当glob模式以较少的麻烦执行相同的工作时,不要使用ls
  • 案例陈述具有惊人的力量

答案 1 :(得分:0)

#!/bin/bash

PRINTQ="/root/docs"

OLDIFS=$IFS
IFS=$(echo -en "\n\b")

for file in $(ls -1 $PRINTQ)
do
        type=$(file --brief $file | awk '{print $1}')
        if [ $type == "PDF" ]
        then
                echo "[*] printing $file with LPR"
                lpr "$file"
        else
                echo "[*] printing $file with OPEN-OFFICE"
                ooffice -p "$file"
        fi  
done

IFS=$OLDIFS

答案 2 :(得分:0)

首先,两个一般的shell编程问题:

  • Do not parse the output of ls.这是不可靠的,完全无用的。使用通配符,它​​们简单而且健壮。
  • 始终在变量替换附近使用双引号,例如"$PrintQueue/$PrintFile",而不是 $PrintQueue/$PrintFile 。如果保留双引号,shell将对变量的值执行通配符扩展和字拆分。除非您知道这是您想要的,否则请使用双引号。命令替换$(command)也是如此。

从历史上看,file的实现具有不同的输出格式,适用于人而不是解析。大多数现代实现都可以选择输出MIME type,这很容易解析。

#!/bin/bash
print_queue="/root/xxx"
for file_to_print in "$print_queue"/*; do
  case "$(file -i "$file_to_print")" in
    application/pdf\;*|application/postscript\;*)
      lpr -r "$file_to_print";;
    application/vnd.oasis.opendocument.*)
      ooffice -p "$file_to_print" &&
      rm "$file_to_print";;
    # and so on
    *) echo 1>&2 "Warning: $file_to_print has an unrecognized format and was not printed";;
  esac
done