Run Shell Script by checking the 32bit or 64bit system architecture

Asked

Viewed 99 times

1

How can I make a script that checks the system architecture and so it would execute the commands for the appropriate architecture, for example:

if 32bit; then

comandos para 32 bits

else

comandos para 64 bits

3 answers

6


I found an answer that detects different types of architectures on Soen, note that each case checks:

#!/bin/bash

HOST_ARCH=$(uname -m)

case "$HOST_ARCH" in
    x86)     HOST_ARCH="x86"          ;;
    i?86)    HOST_ARCH="x86"          ;;
    ia64)    HOST_ARCH="ia64"         ;;
    amd64)   HOST_ARCH="amd64"        ;;
    x86_64)  HOST_ARCH="x86_64"       ;;
    sparc64) HOST_ARCH="sparc64"      ;;
    * )      HOST_ARCH="desconhecido" ;;
esac

echo
echo "A arquitetura do seu sistema é: $HOST_ARCH"
echo

Example in IDEONE: https://ideone.com/iaBg8b

Or you can even simplify it to something like:

#!/bin/bash

HOST_ARCH=$(uname -m)

case "$HOST_ARCH" in
    x86)     HOST_ARCH="32"           ;;
    i?86)    HOST_ARCH="32"           ;;
    ia64)    HOST_ARCH="64"           ;;
    amd64)   HOST_ARCH="64"           ;;
    x86_64)  HOST_ARCH="64"           ;;
    sparc64) HOST_ARCH="64"           ;;
    * )      HOST_ARCH="desconhecido" ;;
esac

if [ $HOST_ARCH = "64" ]; then
   # comandos para 64
elif [ $HOST_ARCH = "32" ]; then
   # comandos para 32
else
   echo "Sistema não suportado";
fi

Example in IDEONE


The response of Miguel looks good, but the else does not guarantee that it is 64-bit, I believe that the best is to save in a variable and use a elif, for example:

HOST_ARCH=$(file /bin/bash | cut -d' ' -f3);

if [ $HOST_ARCH = "32-bit" ]; then

   # comandos para 32 bits

elif [ $HOST_ARCH = "64-bit" ]; then

   # comandos para 64 bits

else
   echo "Sistema não suportado";
fi

1

Below is the check of the system variable LONG_BIT:

if [ $(getconf LONG_BIT) = 64 ]; then
  echo "64bits";
elif [ $(getconf LONG_BIT) = 32  ]; then
  echo "32bits";
else 
  echo "another";
fi

Another option would be the uname -m check that returns:

  • x64, ia64, amd64 and x86_64 would be 64 bits;

  • i686, i586, i486 and i386 would be 32 bits;

1

#!/bin/bash
if [ $(uname -m) = "x86_64" ]; then
    echo "x64"
else
    echo "x86"
fi
  • Tbm works, thank you!

  • 1

    The else does not guarantee that the architecture is x86, assuming that eventually this script can be run on a totally different and unusual architecture.

  • @Guilhermenascimento can give some examples of os/Arch? An elseif instead of Else then?

  • @Tommelo that’s right, um elif for x86 (i686, i586, i486 and i386) and else you would put a echo "desconhecido";

  • On second thought, maybe the uniting is not a good option...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.