【问题标题】:Creating bash script of a complex linux command创建一个复杂的linux命令的bash脚本
【发布时间】:2010-08-18 15:08:19
【问题描述】:

我每天都会使用一些长命令。所以我认为最好有一个 bash 脚本,我可以在其中传递参数,从而节省打字。我想这是 Linux 的常态,但我对它有点陌生。有人可以告诉我怎么做。一个例子是下面的命令

cut -f <column_number> <filename> | sort | uniq -c | 
sort -r -k1 -n | awk '{printf "%-15s %-10d\n", $2,$1}'

所以我想在一个脚本中使用它,我可以在其中传递文件名和列号(最好以任何顺序)并获得所需的输出,而不必每次都输入整个内容。

【问题讨论】:

    标签: linux bash command-line


    【解决方案1】:

    创建一个文件说 myscript.sh -

    #!/bin/bash
    if [ $# -ne 2 ]; then 
    echo Usage: myscript.sh column_number file_path
    exit
    fi
    
    if ! [ -f $2 ]; then
    echo File doesnt exist
    exit
    fi
    
    if [ `echo $1 | grep -E ^[0-9]+$ | wc -l` -ne 1 ]; then
    echo First argument must be a number
    exit
    fi
    
    cut -f 10  $1 $2 | sort | uniq -c | 
    sort -r -k1 -n | awk '{printf "%-15s %-10d\n", $2,$1}'
    

    使用命令chmod +x mytask.sh确保这个文件是可执行的

    您可以像sh myscript.sh 30 myfile.sh./myscript.sh 30 myfile.sh 一样调用它

    上述脚本的第一行指定了您希望在其中执行脚本的 shell。$1 和 $2 指的是第一个和第二个命令行参数。

    关于参数有效性检查:

    1. 第一次检查确保恰好有两个参数传递给脚本。
    2. 第二次检查确保参数二指向的文件存在
    3. 第三次检查确保作为第一个参数传递的数字确实是一个数字。它为此目的使用正则表达式。可能有人为这张支票提供了更好的替代品,但这就是我立即想到的。

    【讨论】:

    • @Gopi 但是如果我想确保文件存在并且列值是数字整数怎么办?
    • 你可以做各种各样的事情,看看这个指南tldp.org/LDP/abs/html
    • @sfactor - 要确定文件是否存在,您需要使用带有文件开关的 if 语句:if [ -f testfile ] then / echo "testfile exists!" / fi 我将把列类型测试留给您。查看 bash 参考手册以获得更多帮助,您可以从这里开始:faqs.org/docs/bashman/bashref_68.html
    • @sfactor 我添加了必需的检查
    • @Gopi - 使用 grep -E ^[0-9]+$ -- + 确保至少存在一位数字。否则你会匹配一个空字符串。
    【解决方案2】:

    要以任何顺序接受文件名和列号,您需要使用选项开关。 Bash 的getopts 允许您指定和处理选项,以便您可以使用scriptname -f filename -c 12scriptname -c 12 -f filename 调用您的脚本。

    #!/bin/bash
    
    options=":f:c:"
    while getopts $options option
    do
        case $option in
            f)
                filename=$OPTARG
                ;;
            c)
                col_num=$OPTARG
                ;;
            \?)
                usage_function    # not shown
                exit 1
                ;;
            *)
                echo "Invalid option"
                usage_function
                exit 1
                ;;
        esac
    done
    shift $((OPTIND - 1))
    if [[ -z $filename || -z $col_num ]]
    then
        echo "Missing option"
        usage_function
        exit 1
    fi
    if [[ $col_num == *[^0-9]* ]]
    then
        echo "Invalid integer"
        usage_function
        exit 1
    fi
    # other checks
    cut -f 10  $col_num "$filename" | ...
    

    【讨论】:

      猜你喜欢
      • 2017-01-26
      • 1970-01-01
      • 2012-01-30
      • 2015-09-03
      • 1970-01-01
      • 1970-01-01
      • 2018-01-08
      • 2018-09-19
      • 2016-03-08
      相关资源
      最近更新 更多