• 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

    • XRECODE3 1.169 by Razvan Serea xrecode3 is a converter and audio-grabber which allows you to convert from mp3, mp2, wma, aiff, amr, ogg, flac, ape, cue, ac3, wv, mpc, mid, cue ,tta, tak, wav, wav(rf64), dts, m4a, m4b, mp4, ra, rm, aac, avi, mpg, vob, mkv, mka, flv, swf, mov, ofr, wmv, divx, m4v, spx, 3gp, 3g2, m2v, m4v, ts, m2ts, adts, shn, tak, xm, mod, s3m, it, mtm, umx, mlp to m4a, alac, ape, flac, mp3, mp4 (using NeroAAC), ogg, raw, wav, wav(rf64), wma, WavPack, mpc, mp2, Speex, ofr, ac3, aiff, tak, snd and Shorten formats. Command Line parameters are supported. XRECODE3 features: Works on XP, Vista, Windows 7, Windows 8, 10 32/64 bit versions and under Wine. Parallel conversion by utilizing power of multi-core CPUs. Support of embedded CUE sheets (for FLAC, WavPack, APE and TAK files). Support of mp4, mka chapters (can split mp4, mka by chapters to any supported format). Built-in Metadata editor with Cover Art support. Has support for LossyWav. Supports portable mode. Merge input files to one large audio file and create CUE sheet. Converting to many formats at once using "Multiple" output mode. Grabbing of multi-channel Audio CDs to the desired format at once. Informative and resizable UI suited even for netbooks. Extracting audio from flv, avi, mov etc. video files (multiple audio streams are supported). Can export/import Metadata to/from external file. Support for 24/32bit audio files. Multilanguage support. Currently program is available in Dutch, English, French, Japanese, Korean, Polish, Russian, Hungarian, Italian, Spanish, Spanish Traditional, Swedish, Brazilian Portuguese, German, Finnish, Bulgarian, Czech, Danish and Chinese (simplified) languages. What's new in XRECODE3: Native 64bit support. Added support for DSD/DST and DFF formats (including handling of SACD ISOs). Added option to extract audio without transcoding. Added option to encode several files to one multi-channel file. Added option to split file into individual track-per-channel for all available output formats. Added option to merge files per folder. Output and Metadata settings are now output format specific. Enhanced Metadata settings. Added support for multiple Cover pictures in Metadata editor. Added 32bit int/float output for formats which support them (e.g. WAV). Added dithering option in Output Settings. Added option to use EBUR128 in Normalize. Added option to Album Mode Normalize. Added option to configure Matrices under Output Settings. Added more output file pattern elements. Tabbed UI. CUE files are now displayed more nicely. Enhanced Shell Extension. XRECODE3 1.169 changelog: FIX: resolved an issue where playlist file names was created with 2 dots before the file extension. FIX: fixed issue with encoding some files to ac3 format. Download: XRECODE3 v1.169 (64-bit) | Portable | ~30.0 MB (Shareware) Download: XRECODE3 v1.169 (32-bit) | Portable Link: XRECODE3 Homepage | XRECODE3 Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • So... Tesla fails, SpaceX fails, not Starlink... I guess karma is a bitch...
    • Basically, they can hire someone with less skill for a lower wage, for example from India, and use AI to bring that employees output up to the level of someone more experienced and expensive. It’s a broad cost-cutting strategy, and plenty of companies are already doing it. With AI involved, the employee just needs to check that the AI's results aren’t complete junk. They don’t actually have to know how to produce the work themselves. You just get one high level employee to triple check who does. The workflow looks like this: AI generates the content, a low-skilled worker filters out anything clearly broken or wrong, and a high-skilled worker gives it a final pass. Instead of hiring a full team of experts, companies can rely on a few at the top while AI and cheaper labour handle the bulk of the process.
    • Aah, always the evil terrorist group. Why not just the Russians, they're worse than any terrorist organisation.
    • LG Electronics sees profit dip but boosts shareholder returns by Paul Hill LG Electronics (LGE) has reported consolidated sales of 20.74 trillion Korean Won (approximately $15.14 billion USD) and an operating profit of 639.4 billion Korean Won (approximately $466.75 million USD) for the second quarter of 2025. The firm saw both its revenue and operating profits decline year-over-year due to external factors such as US tariff policies, ongoing geopolitical issues in the Middle East, and a slowdown in consumer spending. While the company has faced challenges, the company is aiming for what it called qualitative growth by strengthening its subscription services, direct online sales, and business-to-business (B2B) segments. Key areas of growth for LGE include automotive electronics, heating, ventilation, and air conditioning (HVAC) systems, and the webOS platform. The US tariffs are a major headache for companies around the world, given the size of the market there and President Trump's demands for bringing manufacturing to the States. To combat the rising US tariffs, LGE is trying to optimize global production and refine its market-specific approaches for premium and mass-market products. While the company’s profits dipped, it announced an interim dividend of 500 Korean Won (approximately $0.37 USD) per share for both common and preferred, with another payout later in the year that should take the total for 2025 to at least 1,000 Korean Won (approximately $0.73 USD). You must be holding the stock on August 8, 2025, to get the payout on August 22, 2025. The firm also said it will cancel 761,427 common treasury shares on July 31, 2025, making shares more scarce which could increase the value of remaining shares for investors. In terms of LGE’s various business divisions, things were mixed. Its Home Appliance Solution (HS) business achieved year-over-year sales growth, maintaining profitability, thanks to a dual strategy for premium and volume segments and growth in online sales and subscriptions. Its Media Entertainment Solution (MS) business experienced declines in sales and operating profits with the latter turning negative due to market uncertainties and stiff competition. Its Vehicle Solution (VS) business showed growth in sales and operating profit thanks to increased orders from European automotive makers. Finally, its Eco Solution (ES) business saw domestic sales increase, but overseas sales growth was limited due to US tariffs. This led to a slight year-over-year drop in operating profit due to higher costs. Image via Depositphotos.com
  • Recent Achievements

    • Week One Done
      Itbob513626 earned a badge
      Week One Done
    • One Month Later
      Itbob513626 earned a badge
      One Month Later
    • Rookie
      EdwardFranciscoVilla went up a rank
      Rookie
    • Week One Done
      MoJo624 earned a badge
      Week One Done
    • Collaborator
      aeganwn earned a badge
      Collaborator
  • Popular Contributors

    1. 1
      +primortal
      619
    2. 2
      ATLien_0
      243
    3. 3
      Xenon
      160
    4. 4
      Michael Scrip
      124
    5. 5
      +FloatingFatMan
      123
  • Tell a friend

    Love Neowin? Tell a friend!