在 CentOS 上的 bash shell 中,在 ~/.bash_profile 文件中定义函数的正确方法是什么?

在 CentOS 上的 bash shell 中,在 ~/.bash_profile 文件中定义函数的正确方法是什么?

我在 CentOS 上使用 bash shell。我想定义一个运行 PostGres 14 查询并输出结果的函数。

eth_price 2023-12-06 10:05

在我的 ~/.bash_profile 文件中,我定义了

eth_price() {
  timestamp="$1:00"  # Append ":00" to the provided timestamp
  PGPASSWORD=$DB_PASS psql -U $DB_USER -d $DB_NAME -c "select price from cryptocurrencyprice p, cryptocurrency c where c.id = p.crypto_currency_id and c.abbrev = 'ETH' and p.created <= '$timestamp' order by created desc limit 1;"
}

不幸的是,当我跑步时

source ~/.bash_profile

我收到错误

-bash: /home/myuser/.bash_profile: line 31: syntax error near unexpected token `('
-bash: /home/myuser/.bash_profile: line 31: `eth_price() {'

定义我的函数的正确方法是什么?

编辑:

这是版本输出...

$ bash --version
GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

为了进一步隔离问题,我创建了整个 ~/.bashrc 文件,如下所示

# .bashrc

# Source global definitions
if [ -f /etc/bashrc ]; then
        . /etc/bashrc
fi

# Uncomment the following line if you don't like systemctl's auto-paging feature:
# export SYSTEMD_PAGER=

# User specific aliases and functions
eth_price() {
  timestamp="$1:00"  # Append ":00" to the provided timestamp
  PGPASSWORD=$DB_PASS psql -U $DB_USER -d $DB_NAME -c "select price from price p, currency c where c.id = p.id and c.abbrev = 'ETH' and p.created <= '$timestamp' order by created desc limit 1;"
}

有趣的是,这失败了

$ source ~/.bashrc
-bash: /home/myuser/.bashrc: line 12: syntax error near unexpected token `('
-bash: /home/myuser/.bashrc: line 12: `eth_price() {'

但这成功了......

$ sh ~/.bashrc
$ 

相关内容