1

我正在研究一个 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

4

3 回答 3

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
  • 案例陈述具有惊人的力量
于 2011-06-26T11:50:19.073 回答
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
于 2011-06-26T11:49:41.820 回答
0

首先,两个通用的shell编程问题:

  • 不要解析ls. 这是不可靠的,完全没用。使用通配符,它​​们既简单又健壮。
  • 始终在变量替换周围加上双引号,例如"$PrintQueue/$PrintFile"not $PrintQueue/$PrintFile。如果省略双引号,shell 将对变量的值执行通配符扩展和分词。除非您知道这是您想要的,否则请使用双引号。命令替换也是如此$(command)

从历史上看,实现file有不同的输出格式,用于人类而不是解析。大多数现代实现都有一个输出MIME 类型的选项,这很容易解析。

#!/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
于 2011-06-26T12:38:44.603 回答