• 0

Bash comparing command in variable


Question

Hello,

Well I am writing my first bash script today and I've hit a snag. I am trying to compare the SHA1 of a file with what it is supposed to be. Here is an abbreviated version:


#!/bin/bash
clear
csha1='openssl sha1 "dliOS.sh"'
bsha1="SHA1(dliOS.sh)=f2533a75a69ab1cd87d93749449523d65d"
echo "Required SHA1: " $bsha1
echo "File SHA1: " $csha1
if [ $csha1 != $bsha1]
then
echo "SSH doesn't match!"
else
echo "SSH is good."
fi
exit
[/CODE]

The output of my script is:

[CODE]
Required SHA1: SHA1(dliOS.sh)=f2533a75a69ab1cd87d93749449523d65d
File SHA!: openssl sha1 "dliOS.sh"
./test.sh: line 7: [: too many arguments
SSH is good
[/CODE]

I've tried every method to include the command output in a variable to compare it with the SHA1 hash it is supposed to be, but all fail. [The whole programs purpose is to log me into my barracks internet (it logs everybody out after each hour, so my script detects the logout, then logs in) whenever it disconnects and then continues my iOS5 download [downloading at 10kb-20kbs a second, I need resume :(). But I want it to verify that the file is intact when it is done downloading. Also, I can't find any method of obtaining the file size in bytes only, no other bs outpust suck as user [i read the stat, ls, and file man pages].

Thank You.

Link to comment
https://www.neowin.net/forum/topic/1048093-bash-comparing-command-in-variable/
Share on other sites

6 answers to this question

Recommended Posts

  • 0

I revised your script to do what I think you want. I tested it, and it seems to work well. Hopefully this gives you the answer you seek.


#!/bin/bash
clear
fname="dliOS.sh"
csha1=$(sha1sum "$fname" | cut -d ' ' -f 1)
bsha1="SHA1($fname)=f2533a75a69ab1cd87d93749449523d65d"
echo -e "Required SHA1:\t\t" $bsha1
echo -e "File SHA1:\t\t" $csha1
if [ "$csha1" != "${bsha1:$((${#fname}+7))}" ]; then
echo "SSH doesn't match!"
else
echo "SSH is good."
fi
exit 0
[/CODE]

Edit: Just to clarify, the number 7 on line 8 represents the number of characters in "SHA1()=" in the bsha1 variable. Alternatively, you could extract the checksum from the variable like this: $(echo $bsha1 | cut -d '=' -f 2) That alleviates the necessity of the static number in the expression in question.

  • 0

When accessing the contents of a variable, always always always put quotes around the variable. Like this:

my_variable = 'This is a test'
echo "$my_variable"	  # <-- Notice the quotes
# This is a test
[/CODE]

In your case what happened is that your "if" statement read the contents of $csha1 as a list of arguments instead of a string. So the script expanded from this:
[code]if [ $csha1 != $bsha1]

to this

if [ openssl sha1 "dliOS.sh" != SHA1(dliOS.sh)=f2533a75a69ab1cd87d93749449523d65d ]

The test command (which is the opening square bracket) expects four arguments:

  1. Left operand
  2. Operator
  3. Right Operand
  4. A closing square bracket.

When Bash expanded your variables, it actually saw 6 arguments, since the contents of $csha1 was read as a list of arguments. By putting your variables inside double quotes, the if statement will read them as strings (as you were trying to do) correctly.

Also as Lant said, you need to use backticks to execute a command and store the output, although now the $() syntax is preferred, which is what you can see on line 4 of xorangekiller's response.

Hope this helps :)

  • 0
  On 30/12/2011 at 23:06, Majesticmerc said:

When accessing the contents of a variable, always always always put quotes around the variable. Like this:

my_variable = 'This is a test'
echo "$my_variable"	  # <-- Notice the quotes
# This is a test
[/CODE]

In your case what happened is that your "if" statement read the contents of $csha1 as a list of arguments instead of a string. So the script expanded from this:
[code]if [ $csha1 != $bsha1]

to this

if [ openssl sha1 "dliOS.sh" != SHA1(dliOS.sh)=f2533a75a69ab1cd87d93749449523d65d ]

The test command (which is the opening square bracket) expects four arguments:

  1. Left operand
  2. Operator
  3. Right Operand
  4. A closing square bracket.

When Bash expanded your variables, it actually saw 6 arguments, since the contents of $csha1 was read as a list of arguments. By putting your variables inside double quotes, the if statement will read them as strings (as you were trying to do) correctly.

Also as Lant said, you need to use backticks to execute a command and store the output, although now the $() syntax is preferred, which is what you can see on line 4 of xorangekiller's response.

Hope this helps :)

Aye that explains everything perfectly! I originally was going to create a PHP script as that is what I am best at, but I felt it best to use the shell for this.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Another Linux utility is being rewritten in Rust by David Uzondu Greenboot, the health check tool originally written in bash, is getting a rewrite in Rust, courtesy of engineers at Red Hat. This useful tool started in mid‑2018 as a Google Summer of Code project for Fedora IoT, designed to keep atomically updated systems from self-destructing after a bad update. At its heart, Greenboot is a framework that hooks into systemd to run health checks every time a machine boots. It looks for scripts in specific directories; anything in /etc/greenboot/check/required.d/ absolutely must pass. If a required script fails, Greenboot triggers a reboot to retry. After a few failed attempts, it executes scripts in /etc/greenboot/red.d/ and initiates a system rollback to the last known-good deployment, preventing an update from bricking your system. When all required checks succeed, it runs scripts from /etc/greenboot/green.d/ and marks the boot as successful by setting a GRUB environment variable. This whole process is kicked off by the greenboot-healthcheck.service before systemd's normal boot-complete.target is reached. As for why Red Hat is choosing this rewrite, it comes down to creating a more robust and secure utility. This is definitely not the only *-rs tool rewrite we have seen lately; you have probably heard about sudo-rs, which is a project to build a memory-safe replacement for the classic sudo utility. Building these fundamental system components in a memory-safe language like Rust helps eliminate entire categories of security vulnerabilities. According to the official Fedora change proposal, the rewrite expands support for both bootc and rpm-ostree based systems, whereas the original Bash version was built only for rpm-ostree. Red Hat developers have submitted a proposal to ship this new Rust version in Fedora 43. According to Phoronix, while the plan still needs a final vote from the Fedora Engineering and Steering Committee, it looks very likely to be approved. For current Fedora IoT users, the change promises to be a simple, seamless upgrade.
    • Elden Ring Nightreign will finally gain ‘Duo Expeditions' next week by Pulasthi Ariyasinghe FromSoftware's latest project, Elden Ring Nightreign, delivered a multiplayer-focused experience for the first time. While the title offered solo runs as an alternative to its standard three-player Trio Expeditions, Duos were surprisingly missing at launch. A couple of months later, the developer is finally delivering this highly requested feature for the hit roguelike. On social media, the studio confirmed that Duo Expeditions will be hitting Elden Ring Nightreign with the next update, patch 1.02, for the game on July 30. Check out the newly released trailer showing off this mode below. As we mentioned in our review of Elden Ring Nightreign, everything from enemy health, boss aggression, player damage, and even XP gain changes depending on how many players are in the Expedition. A post-launch update even tweaked the difficulty to favor solos as well. Duos should have the same changes being applied, with the mode being easier than trios but harder than solos to complete. Making sure the difficulty is properly balanced has previously been given as the reason why the Duos mode has taken a while to come in. FromSoftware also confirmed that patch 1.02 will have a range of more quality-of-life improvements on the UI side. This will include more Relics filtering options, making custom builds easier to construct before going on new runs, as seen below. Publisher Bandai Namco also announced this week that the Elden Ring Shadow of the Erdtree expansion for the original open-world Soulslike recently passed 10 million players. Meanwhile, this Elden Ring Nightreign spin-off now has over 5 million players, making both massive successes for the publisher. While FromSoftware is now focusing on other projects, Bandai Namco isn't done with the Elden Ring universe just yet either, as a live-action movie has now been confirmed to be in development too.
    • Or you ignore the part where @Michael Scrip answered you directly.
    • The reasons for Microsoft being in near perpetual state of reorganization for two years is due to the 6 CapEx acquisitions between Jan 2022 and Jan 2023, Blizzard, Oribi, Minit, Miburo, Lumenisity and Fungible. There were 15 CapEx acquisitions in 2021 alone. Much like the Borg, Microsoft assimilates knowledge instead of expending resources on learning and development. 10 gaming companies, 3 AI and 1 data modeling companies since 2018. But then this is in the founding DNA of Microsoft, MS DOS wasn't made by MS, Windows was based on the Apple Mac and Xerox PARC Alto....and on and on. (To be fair Apple's Lisa and Mac were from the Alto also)
    • Can't get a pic of the physical server as it's in a DC, but what i'm running on it is doable. All for my own use except one VM used by a friend to run her site and other things.
  • Recent Achievements

    • Very Popular
      d4l3d earned a badge
      Very Popular
    • Dedicated
      Stephen Leibowitz earned a badge
      Dedicated
    • Dedicated
      Snake Doc earned a badge
      Dedicated
    • One Month Later
      Philsl earned a badge
      One Month Later
    • One Month Later
      armandointerior640 earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      629
    2. 2
      ATLien_0
      238
    3. 3
      Xenon
      163
    4. 4
      neufuse
      123
    5. 5
      +FloatingFatMan
      123
  • Tell a friend

    Love Neowin? Tell a friend!