【问题标题】:Run Command on Multiple of Files or Single File在多个文件或单个文件上运行命令
【发布时间】:2015-01-30 02:37:11
【问题描述】:

我需要使用 pnmtojpeg 将几个 pnm 图像文件转换为 jpeg。所以我使用了这个脚本,我将其命名为“pnm2jpg”:

for f in *.pnm;
  do pnmtojpeg -quality=85 "$f" > "${f%.pnm}.jpg";
done

这很好用。但是,我想进一步调整它,以便它也可以用于单个文件。

也就是说,如果命令行中没有指定文件,则处理所有文件。

$ pnm2jpg thisfile.pnm  # Process only this file.

$ pnm2jpg  # Process all pnm files in the current directory.

非常感谢您的洞察力-谢谢。

【问题讨论】:

    标签: bash shell scripting command


    【解决方案1】:

    类似:

    #!/bin/bash
    
    if [[ -z "$1" ]]; then
        for f in *.pnm; do
            pnmtojpeg -quality=85 "$f" > "${f%.pnm}.jpg"
        done
    else
        pnmtojpeg -quality=85 "$1" > "${1%.pnm}.jpg"
    fi
    

    如果您在没有参数的情况下执行pnm2jpg,则会处理if 块。

    如果您执行pnm2jpg thisfile.pnm,则处理else 块。

    【讨论】:

    • 感谢 user3439894,这看起来很棒。你能解释一下双括号和'-z'是什么意思吗?
    • 它可以用一个或两个方括号编写,我更喜欢使用两个,因为这是我使用的编辑器 (Sublime) 中的默认设置。看看BashFAQ/031Introduction to if。如果您需要进一步解释,请告诉我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-08
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    • 2018-09-21
    相关资源
    最近更新 更多