繁体   English   中英

Linux Shell脚本:在函数中使用别名

[英]Linux shell scripting: Using alias in a function

我使用一个名为ThousandsDotting别名来添加点. 每个3个数字(数千个经典点),因此100000变为100.000

它在shell中可以正常工作,但在function中则不能 示例文件example.sh

#!/bin/bash 
function test() {
  echo "100000" | ThousandsDotting
}
alias ThousandsDotting="perl -pe 's/(\d{1,3})(?=(?:\d{3}){1,5}\b)/\1./g'"
test

如果我运行它,这就是我得到的:

$ ./example.sh
example.sh: line 3: ThousandsDotting: command not found.

什么是正确的方式来 (或使用没有管道,不管)stdout数据这个perl一个函数命令我的Bash shell脚本?

默认情况下,别名在bash中受限制,因此只需启用它即可。

    #!/bin/bash

    shopt -s expand_aliases
    alias ThousandsDotting="perl -pe 's/(\d{1,3})(?=(?:\d{3}){1,5}\b)/\1./g'"
    function test() {
      echo "100000" | ThousandsDotting
    }
    test

产量

100.000

在BASH中, 别名不被继承

更好的方法是创建一个函数:

ThousandsDotting() { perl -pe 's/(\d{1,3})(?=(?:\d{3}){1,5}\b)/\1./g' "$1"; }

然后,您可以将其用作流程替换

ThousandsDotting <(echo "100000")
100.000

alias在交互式bash 更改

#!/bin/bash

#!/bin/bash -i

man bash

If the -i option is present, the shell is interactive.

别名不会在bash中扩展,不能用作 您可以启用它们,有关更多信息,请参阅BASH的永恒指南http://tldp.org/LDP/abs/html/aliases.html

您可以使用bash提供的常规工具来实现与宏相同的功能:

#!/bin/bash
function test() {
    echo "100000" | perl -pe 's/(\d{1,3})(?=(?:\d{3}){1,5}\b)/\1./g'
}
test

您可以通过使函数具有参数来改进此方法:通过这种方式,您可以将任何参数传递给函数test以使用别名获得您将拥有的参数:

#!/bin/bash

function test() {
    perl -pe 's/(\d{1,3})(?=(?:\d{3}){1,5}\b)/\1./g' "$1"
}

test 100000

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM