ppeddi ppeddi - 9 months ago 74
Bash Question

unix unary operator error

I am trying to find a string in the input file path and replace it different file path if it matches.

Below is the code.


echo $FilePath
declare -i idx b
idx= expr index $FilePath 'Forecast'
echo $idx
if [ $idx -gt $b ]
echo $arch_dir



echo statement properly displays the value as some number but in the if statement, I am getting unary operator error .

Can anyone please correct me where I am missing

Answer Source

It appears you have not defined the b variable, so when you write

if [ $idx -gt $b ]

the shell sees this after expanding the variables

if [ 12 -gt  ]

Use one of these forms:

if [ "$idx" -gt "$b" ]    # use quotes to maintain the operators as words
if [[ $idx -gt $b ]]      # the [[ form does not require quoting
if ((idx > b))            # use arithmetic expression

The first form will still throw an error if b is unset:

$ declare -i idx=12 b
$ [ "$idx" -gt "$b" ] && echo yes
bash: [: : integer expression expected
$ [[ $idx -gt $b ]] && echo yes
$ ((idx > b)) && echo yes