Comparing variables in shell scripts

I have a project that includes shell scripts and comparing values ​​/ variables inside them. I have looked at variable comparisons here and elsewhere, and I have tried all the various examples given, but I am encountering something that is not being advertised. OS - Solaris10

I created the following script as a learning experience -

#!/bin/ksh stest() { if $X = $Y then echo they're the same else echo they're notthe same fi } X=a Y=a stest echo completed 

I keep getting some variations of the following:

using sh or ksh shell -

 #./test.sh ./test.sh[2]: a: not found completed 

using the bash shell -

 #./test.sh ./test.sh: line 5: a: command not found completed 

I tried to include the line if $X = $Y in brackets and double brackets and I will return

 [a: not found 

or

 [[a: not found 

If I change the variables X and Y to the number "1", I get the same thing -

 ./test.sh[2]: 1: not found 

I tried wrapping things in single quotes, double quotes, and back quotes.

Any help is appreciated.

+6
source share
2 answers

After if you need a shell command, as elsewhere. $X = $Y parsed as a shell command, that is, $X interpreted as the command name (assuming the value of the variable is one word).

You can use the command [ (also available as test ) or the special syntax [[ … ]] to compare two variables. Note that you will need spaces inside the brackets: the brackets are a separate token in the shell syntax.

 if [ "$X" = "$Y" ]; then 

or

 if [[ "$X" = "$Y" ]]; then 

[ … ] works in any shell, [[ … ]] only in ksh, bash and zsh.

Note that you need double quotes around variables¹. If you leave the quotation marks around, the variable will be split into several words, and each word will be interpreted as a template template. This does not happen inside [[ … ]] , but the right side = interpreted as a template template. Always put double quotation marks around substitution variables (unless you want the variable value to be used as a list of file name match patterns, not as a string).

¹ Except for the $X syntax [[ … ]] .

+7
source

This KornShell (ksh) script should work:

soExample.ksh

 #!/bin/ksh #Initialize Variables X="a" Y="a" #Function to create File with Input #Params: 1} stest(){ if [ "${X}" == "${Y}" ]; then echo "they're the same" else echo "they're not the same" fi } #----------- #---Main---- #----------- echo "Starting: ${PWD}/${0} with Input Parameters: {1: ${1} {2: ${2} {3: ${3}" stest #function call# echo "completed" echo "Exiting: ${PWD}/${0}" 

Output:

 user@foo :/tmp $ ksh soExample.ksh Starting: /tmp/soExample.ksh with Input Parameters: {1: {2: {3: they're not the same completed Exiting: /tmp/soExample.ksh 

ksh version:

 user@foo :/tmp $ echo $KSH_VERSION @(#)MIRBSD KSH R48 2013/08/16 
+1
source

Source: https://habr.com/ru/post/959005/


All Articles