0

我写了一个美化 git log 输出的函数(解决 git log 输出中数据和时间用不同颜色提到的问题)。

function gl() {
my_date=();
my_time=();

    while IFS= read -r line; do
        my_date+=( $(date +"%d-%m-%Y" -d @$line) )
        my_time+=($(date +"%H:%M" -d @$line))
    done < <( git log --format="%at" )

    for (( n=0; n<${#my_date[@]}; n++ )); do
        git --no-pager log -1 --skip=$n --pretty=format:"%C(#d33682)%h %C(#859900)${my_date[$n+1]} %C(#b58900)${my_time[$n+1]} %C(#6c71c4)%ce %C(#2aa198)%s";
        printf "\n";
    done

}

到目前为止,一切都很好。

然后,我在 bash 终端中使用以下代码将此函数移植为 git 别名:

git config --global alias.l '!f(){
my_date=();
my_time=();

while IFS= read -r line; do
    my_date+=( $(date +"%d-%m-%Y" -d @$line) )
    my_time+=($(date +"%H:%M" -d @$line))
done < <( git log --format="%at" )

for (( n=0; n<${#my_date[@]}; n++ )); do
    git --no-pager log -1 --skip=$n --pretty=format:"%C(#d33682)%h %C(#859900)${my_date[$n+1]} %C(#b58900)${my_time[$n+1]} %C(#6c71c4)%ce %C(#2aa198)%s";
    printf "\n";
done
}; f'

现在每次我尝试使用git l时,它都会说f: 2: Syntax error: "(" unexpected (expecting "}")

这里可能是什么问题?

4

1 回答 1

1

您正在编写的脚本包含几个 bashism。Git 调用/bin/sh,在您的系统上不是 bash。在 Debian 和 Ubuntu 上,它是 dash,它更快但功能更少。

Debian指定了您可能期望在 中的特性/bin/sh,这些特性基本上是在 POSIX 中找到的,加上test -aand test -olocal、以及对andecho -n的一些扩展。这些通常是您可以在典型的开源操作系统上使用的功能的安全子集。killtrap/bin/sh

您使用的第一个非便携式结构是 shell 数组。这些仅存在于 bash 和 zsh 中,并且不可移植。此外,使用三部分的 for 循环也是一种拙劣的做法。POSIX sh 只有for name in list语法。的使用function同样是不可移植的。

进程替换 ( <()) 的使用也是不可移植的。您需要将该git log命令用作管道的开头,但由于通常管道的各个部分都编写在子shell 中,因此如果您想正确捕获变量,则需要明确子shell 的范围。

我编写函数的方式是这样的:

gl() {
    git log --format="%at" | (
    n=0;
    while IFS= read -r line
    do
        date=$(date +"%d-%m-%Y" -d @$line)
        time=$(date +"%H:%M" -d @$line)
        git --no-pager log -1 --skip=$n \
            --pretty=format:"%C(#d33682)%h %C(#859900)$date %C(#b58900)$time %C(#6c71c4)%ce %C(#2aa198)%s%n"
        n=$((n + 1))
    done)
}
于 2020-10-17T23:50:51.877 回答