Search code examples
linuxbashshell64-bitx86-64

Error when checking for substring in Bash


I'm quite new to shell scripting and have encountered an issue when trying to check for substrings within a string. I want to build code that checks if you are running a 64bit-based system. This is indicated by the output of the uname -m && cat /etc/*release command by the x86_64 in the first line.

Here's my code:

INFO=$(uname -m && cat /etc/*release)
if [ "$INFO" == *"x86_64"* ]
then
    echo "You are running a 64bit-based system!"
else
    echo "Your system architecture is wrong!"
    exit
fi

Although I run a 64-bit based system and the x86_64 shows up in the output of my command, the if statement still returns false, so I get the output Your system architecture is wrong!. It should be the opposite. Can someone help me out by identifying what I did wrong? I also accept general suggestions for improving my approach, but in the first place, I'd like to know where the bug is.

Many thanks for your help!


Solution

  • [
    

    The command [ is equivalent to test command. test doesn't support any kind of advanced matching. test can compare strings with = - comparing strings with == in test is a bash extension.

    By doing:

    [ "$INFO" == *"x86_64"* ]
    

    You are actually running command like [ "$INFO" == <the list of files that match"x86_64"pattern> ] - the *"x86_64"* undergoes filename expansion. If you would have a file named something_x86_64_something it would be placed there, the same way cat *"x86_64"* would work.

    The bash extensions [[ command supports pattern matching. Do:

    if [[ "$INFO" == *"x86_64"* ]]
    

    For portable scripting that will always work with any kind of posix shell use case:

    case "$INFO" in
    *x86_64*) echo yes; ;;
    *) echo no; ;;
    esac