LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   bash script and reading from file into variable (https://www.linuxquestions.org/questions/linux-newbie-8/bash-script-and-reading-from-file-into-variable-4175703052/)

bomberb17 11-03-2021 08:53 PM

bash script and reading from file into variable
 
I have the following script named test.sh:

Code:

#!/bin/bash

flag=`cat ~/flag`
if [ "$flag" == "$1" ]; then
    echo OK
else
    echo FAIL
fi

Then I run the following:

Code:

$ echo 1 > ~/flag
$ ./test.sh
FAIL

Can someone help me understand why the first condition is not satisfied?

michaelk 11-03-2021 09:11 PM

The script looks like it worked as expected.

Without entering a command line argument when you ran it $1 is empty and therefore not equal to 1.

astrogeek 11-03-2021 09:18 PM

You have set the contents of the file flag to 1.

Your script reads the contents of that file into the variable $flag then your test compares the contents of that variable to the contents of the positional variable $1, which is empty at that point, so the test fails...

Try setting the positional variable and see what happens...

Code:

$ echo 1 > ~/flag
$ ./test.sh 1

The positional variables correspond to the command line args with $0 always being the command name, $1 being the first argument, $2 the second, etc.

^^^ michaelk types faster than I do - what he said!

bomberb17 11-03-2021 09:24 PM

Thank you for your replies.
I actually don't want to have a command line argument.
My goal is to make a script that decides its conditional argument based on a variable fetched from a file on disk.
So if the file contents is "1" then output "OK", else output "FAIL".
How would I fix my script to make this happen?

Mechanikx 11-03-2021 09:35 PM

You would want something like this:

Quote:

#!/bin/bash

flag=`cat ~/flag`
if [ "$flag" -eq 1 ]; then
echo OK
else
echo FAIL
fi

bomberb17 11-03-2021 09:49 PM

Quote:

Originally Posted by Mechanikx (Post 6298191)
You would want something like this:

Ah I see! So "-eq" instead of "==". Thanks!

chrism01 11-03-2021 10:00 PM

Only for num; for str it's still '=='
Code:

if [[ $flag == 'yourstringhere' ]]
In this case it appears you really do want the numeric, so this is just for your info ...

pan64 11-04-2021 01:24 AM

Quote:

Originally Posted by bomberb17 (Post 6298192)
Ah I see! So "-eq" instead of "==". Thanks!

not only use -eq for numbers, but use 1 on the right side, which is a number (or actually can be a string too), but $1 would be a variable ([almost] everything beginning with a $ is a variable) which was not initialized.

A comment: it is actually irrelevant if you compare 1 to 1 as numbers or as strings, the result will be exactly the same.


All times are GMT -5. The time now is 01:43 AM.