0

I am trying to write a script that checks whether unzip is installed on a RHEL server. If it is installed, the script should proceed, but if not, the following message should be displayed:

Unzip package is not installed.

However, I am trying to be careful and consider that the versions may differ from server to server and I am not sure if I can use a wild card. Below is an example of what I am looking for.

UNZIP='rpm -qq unzip'
If [$UNZIP = unzip*] then 'RUN COMMAND' else echo "Unzip is not installed."
  • 2
    Terminate the if statement with fi. Put semicolon before then. If you could paste your bash --version it would help – Attersson Jun 22 '18 at 20:08
  • In bash `[]` is an alias for the `test` command. It isn't recognized unless you put a space after the `[` and before the `]`. Also, you missed a semicolon after `]`. All in all, it should look like `[ ]; then ...`. And as @Attersson said, you need to terminate the if-else with a `fi`. – jdc Jun 22 '18 at 20:08
  • Seems like you need to read a tutorial on shell scripting, you have lots of basic syntax errors. – Barmar Jun 22 '18 at 20:35

1 Answers1

1

You could try something like:

unzip_package="$(rpm -qq unzip)"
if [[ $unzip_package =~ ^unzip.*$ ]]; then
   # ... run command
else
   echo "Unzip is not installed."
fi

Here's a few comments on your code:

1) To run a command in subshell and catch the output in a variable, there's two syntax :

var="$(command)"
var=`command`

But not:

var='command'

2) You need space inside brackets in your test:

[ -z "$unzip" ]: [ is an alias of the test command (or a builtin in bash with same behavior). You should also protect your operands with douple quotes when you use this syntax.

[[ -z $unzip ]]: available since KSH88 (in my memory) and allow more powerfull stuffs like testing regexp since bash 4+ with the =~ operator.

You should see this reminder to get more details.

3) You miss a fi to close the if statement

4) Be careful with the case of statements: if and not If

5) You also miss multiples semicolons:

if <cmd1>; then <cmd2>; else <cmd3>; fi

Or:

if ...; then
  # do some stufs
else
  # ...
fi

Or:

if .... 
then
  # do some stufs
else
  # ...
fi

To conclude you really should learn a little bit more the basics of shell syntax and statements. Here's a really good guide for Bash.

Idriss Neumann
  • 3,760
  • 2
  • 23
  • 32
  • To put the if statement on one line, you need semicolons in (perhaps) unexpected places: `if test-commands; then commands; else commands; fi` – glenn jackman Jun 22 '18 at 20:36
  • Command substitution syntax of `$( ... )` is *not* specific to bash, it is allowed by POSIX: "*Command substitution allows the output of a command to be substituted in place of the command name itself. Command substitution shall occur when the command is enclosed as follows: $(command) or (backquoted version): \`command\`*" – cdarke Jun 22 '18 at 21:40
  • Thanks, I've fixed my answer. – Idriss Neumann Jun 23 '18 at 06:25