开发者

Check execute command after cheking file type

I am working on a bash script which execute a command depending on the file type. I want to use the the "file" option and not the file extension to determine the type, but I am bloody new to this scripting stuff, so if someone can help me I would be very thankful! - Thanks!

Here the script I want to include the function:

 #!/bin/bash

 export PrintQueue="/root/xxx";

 IFS=$'\n'

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

     lpr -r ${PrintQueue}/${PrintFile}开发者_如何学编程;

 done

The point is, all files which are PDFs should be printed with the lpr command, all others with ooffice -p


You are going through a lot of extra work. Here's the idiomatic code, I'll let the man page provide the explanation of the pieces:

#!/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

Some notable points:

  • using sh instead of bash increases portability and narrows the choices of how to do things
  • don't use ls when a glob pattern will do the same job with less hassle
  • the case statement has surprising power


First, two general shell programming issues:

  • Do not parse the output of ls. It's unreliable and completely useless. Use wildcards, they're easy and robust.
  • Always put double quotes around variable substitutions, e.g. "$PrintQueue/$PrintFile", not $PrintQueue/$PrintFile. If you leave the double quotes out, the shell performs wildcard expansion and word splitting on the value of the variable. Unless you know that's what you want, use double quotes. The same goes for command substitutions $(command).

Historically, implementations of file have had different output formats, intended for humans rather than parsing. Most modern implementations have an option to output a MIME type, which is easily parseable.

#!/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


#!/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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜