Home > Blockchain >  Shell script unknown operand alpine
Shell script unknown operand alpine

Time:12-14

I am running into a problem where my shell script doesn't work if the variable is not set/set to empty string.

For this I am using the alpine image

docker run -dt alpine
docker exec -it <container> sh

Here is the problematic code:

x=""
sh -c "if [ "$x" != "required" ]; then sed; fi"

When x is not set, I get the error:

sh: required: unknown operand

This seems to only be the problem on an empty string. If I set x="lkajsdfasl", it will work just fine.

This just breaks down on an empty string/not set.

Due to the way my docker-compose is setup, I can only use sh and have to use sh -c

CodePudding user response:

It's a quoting issue. Use single quotes around the command like this

sh -c 'if [ "$x" != "required" ]; then sed; fi'
  • Related