提问人:slyfox1186 提问时间:6/8/2023 更新时间:6/9/2023 访问量:65
loop if 哪个命令,直到第一个匹配并将其存储在变量中
loop if which command until the first match and store it in a variable
问:
我正在尝试查找操作系统上安装的 C 和 C++ 编译器的最高版本。
我正在尝试优化我的代码,而不是占用 25 行并一遍又一遍地重写一堆命令。if which
任何人都可以在任何版本的发行版上访问该脚本,因此列表可能很长且充满可能性,我希望最新版本来运行该版本。
我发布此内容的原因是因为我在安装时不断取回匹配项,并在手动运行时显示......那么为什么它只匹配较低的版本呢?gcc-11
gcc-12
which 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
答:
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
评论
set -x
which
for c in "${c_compilers[@]}"; do command -v "$c" &> /dev/null && { CC="$c"; break; }; done
?