ppeddi ppeddi - 1 month ago 20
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.

*

FilePath='/GAMER/WIP/Forecast'
echo $FilePath
fnd='WIP'
repl='Archive'
declare -i idx b
idx= expr index $FilePath 'Forecast'
echo $idx
if [ $idx -gt $b ]
then
arch_dir=${FilePath/$fnd/$repl}
echo $arch_dir

fi


*

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

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
yes
$ ((idx > b)) && echo yes
yes