我正在尝试选择Bash中某些输出的一部分,但无法弄清楚放置过滤器的位置,并对获得的输出感到困惑。
我从
开始declare -a pythons=("python" "python2" "python3")
for p in "${pythons[@]}"
do
echo "$p: $($p --version 2>&1) in $(which $p)" && for i in $(which -a $p); do echo " $i ($($i --version 2>&1))"; done && echo;
done
已经工作了多年以产生我期望的输出,即
python: Python 2.7.15 in /usr/local/bin/python
/usr/local/bin/python (Python 2.7.15)
/usr/bin/python (Python 2.7.10)
python2: Python 2.7.15 in /usr/local/bin/python2
/usr/local/bin/python2 (Python 2.7.15)
python3: Python 3.7.0 in /usr/local/bin/python3
/usr/local/bin/python3 (Python 3.7.0)
但现在产生
python3: Python 3.7.0 (default, Jun 29 2018, 20:13:13)
[Clang 9.1.0 (clang-902.0.39.2)] in /usr/local/bin/python3
/usr/local/bin/python3 (Python 3.7.0 (default, Jun 29 2018, 20:13:13)
[Clang 9.1.0 (clang-902.0.39.2)])
进行最终分组。
我认为我可以通过在每个egrep -o 'Python\s[0-9\\.]+'
之后加上python --version
来简单地解决此问题,
for p in "${pythons[@]}"
do
echo "$p: $($p --version | egrep -o 'Python\s[0-9\\.]+' 2>&1) in $(which $p)" && for i in $(which -a $p); do echo " $i ($($i --version | egrep -o 'Python\s[0-9\\.]+' 2>&1))"; done && echo;
done
但这令我感到惊讶,将Python 2版本拉到了我期望的行之前的单独行中
Python 2.7.15
python: in /usr/local/bin/python
Python 2.7.15
/usr/local/bin/python ()
Python 2.7.10
/usr/bin/python ()
Python 2.7.15
python2: in /usr/local/bin/python2
Python 2.7.15
/usr/local/bin/python2 ()
python3: Python 3.7.0 in /usr/local/bin/python3
/usr/local/bin/python3 (Python 3.7.0)
我认为我已经完全迷失了将输出发送到哪里的问题,并且需要帮助来弄清楚我在哪里(可能是非常基本的)Bash脚本错误。
答案 0 :(得分:1)
该问题似乎与您将2>&1
的位置移到grep
的右侧有关。使用这个:
for p in "${pythons[@]}"
do
echo "$p: $($p --version 2>&1 | egrep -o 'Python\s[0-9\\.]+') in $(which $p)" && for i in $(which -a $p); do echo " $i ($($i --version 2>&1 | egrep -o 'Python\s[0-9\\.]+'))"; done && echo;
done