loop if 哪个命令,直到第一个匹配并将其存储在变量中

loop if which command until the first match and store it in a variable

提问人:slyfox1186 提问时间:6/8/2023 更新时间:6/9/2023 访问量:65

问:

我正在尝试查找操作系统上安装的 C 和 C++ 编译器的最高版本。

我正在尝试优化我的代码,而不是占用 25 行并一遍又一遍地重写一堆命令。if which

任何人都可以在任何版本的发行版上访问该脚本,因此列表可能很长且充满可能性,我希望最新版本来运行该版本。

我发布此内容的原因是因为我在安装时不断取回匹配项,并在手动运行时显示......那么为什么它只匹配较低的版本呢?gcc-11gcc-12which gcc-12

#!/bin/bash

clear

c_compilers=(gcc-13 gcc-12 gcc-11 gcc-10 gcc-9 gcc clang-16 clang-15 clang-14 clang-13 clang-12 clang-11 clang-10 clang)
cxx_compilers=(g++-13 g++-12 g++-11 g++-10 g++-9 g++ clang++-16 clang++-15 clang++-14 clang++-13 clang++-12 clang++-11 clang++-10 clang++)

for i in ${c_compilers[@]}
do
    cc_match="$(which $i)"
    if [ -n "$cc_match" ]; then
        CC="$cc_match"
        break
    fi
done

for i in ${cxx_compilers[@]}
do
    cxx_match="$(which $i)"
    if [ -n "$cxx_match" ]; then
        CXX="$cxx_match"
        break
    fi
done

echo $PATH
echo $CC
echo $CXX
数组 bash for 循环 if-statement 匹配

评论

2赞 Gordon Davisson 6/8/2023
尝试在此之前放置,以便在运行时获取执行跟踪,以便您可以确切地看到它出了问题。另外,我不认为这是相关的,但是在很多地方,您确实应该对变量引用进行双引号;shellcheck.net 会指出它们。set -x
6赞 glenn jackman 6/8/2023
有一些内置命令比 -- stackoverflow.com/q/592620/7552 更好which
0赞 Renaud Pacalet 6/8/2023
for c in "${c_compilers[@]}"; do command -v "$c" &> /dev/null && { CC="$c"; break; }; done?

答:

0赞 slyfox1186 6/9/2023 #1

由于没有其他人有答案,我利用评论中的建议提出了这个问题。

#!/bin/bash
clear

# find the highest gcc version you have installed and set it as your CC compiler
type -P 'gcc' && export CC='gcc'
type -P 'gcc-9' && export CC='gcc-9'
type -P 'gcc-10' && export CC='gcc-10'
type -P 'gcc-11' && export CC='gcc-11'
type -P 'gcc-12' && export CC='gcc-12'
type -P 'gcc-13' && export CC='gcc-13'

# find the highest g++ version you have installed and set it as your CXX compiler
type -P 'g++' && export CXX='g++'
type -P 'g++-9' && export CXX='g++-9'
type -P 'g++-10' && export CXX='g++-10'
type -P 'g++-11' && export CXX='g++-11'
type -P 'g++-12' && export CXX='g++-12'
type -P 'g++-13' && export CXX='g++-13'

echo
echo $CC
echo
echo $CXX