I need to write a bash script where i have to check whether the Linux kernel is 32 bit or 64 bit.
I am using uname -a command, and it gives me x86_64 result. But I believe I can not use it in the generic way because result may differ if some one using non x86 architecture.
How to check for 32-bit / 64-bit kernel for Linux?
I came up with the following. It assumes that init
is used (some distros have switched to other loaders, but it should be easy to get a list of reasonably often used ones) and that you use ELF
, not a.out
or other nowadays exotic executable format. These seem to be sane assumptions for most systems, but probably they may be broken in embedded systems, etc. Still, the general idea should be possible to adapt (get to the init
process or equivalent and check its bitness using file
). If you are running as root, instead of going through the file's path, you could use file $(sudo readlink -e /proc/1/exe)
(PID 1 being init
is probably more portable than assuming anything about its path).
if file /sbin/init | fgrep 'ELF 64-bit' &>/dev/null; then
echo "64-bit"
else
echo "not 64-bit"
fi
The question is rather: what do you intend to achieve by knowing whether you are on 32 or 64? What are the consequences of being on a hypothetical 128-bit environment? And what part actually is being tested for N-bitness? A CPU may support running in 64-bit mode, but the environment be 32-bit. Furthermore, the environment itself may be a mixed-mode; consider running a 64-bit kernel with a 32-bit userspace (done on a handful of classic RISCs). And then, what if the userspace is not of a homogenous bitness/executable format? That is why getconf LONG_BIT
is equally pointless to use, because it depends on how it was compiled.
$ /rt64/usr/bin/getconf LONG_BIT
64
$ /usr/bin/getconf LONG_BIT
32
$ file /usr/bin/getconf /rt64/usr/bin/getconf
/usr/bin/getconf: ELF 32-bit MSB executable, SPARC32PLUS, V8+ Required, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.4, not stripped
/rt64/usr/bin/getconf: ELF 64-bit MSB executable, SPARC V9, relaxed memory ordering, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.4, not stripped
$ uname -m
sparc64
You could query the system for the size of a long int
:
getconf LONG_BIT
But I'm not sure if this is completely portable to all different architectures.
A quite reliable way to determine the supported executable architecture:
A featured function to do this:
# Gets the supported executable architecture
# >: 32-bit | 64-bit
getRunArch() {
local arch
local IFS=' '
read -r _ arch _ <<< $(file --dereference --brief "$(which ls)")
echo -n "${arch}"
}
Testing this:
echo "Supported run-time architecture is: $(getRunArch)"
Supported run-time architecture is: 64-bit
Slightly more reliable than:
getconf LONG_BIT
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With